package com.zhiche.lisa.lspm.service.driver.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zhiche.lisa.core.enums.*;
import com.zhiche.lisa.core.enums.exception.DriverExceptionEnum;
import com.zhiche.lisa.core.supports.BaseException;
import com.zhiche.lisa.core.supports.RestfulResponse;
import com.zhiche.lisa.core.utils.Account.AccountUtil;
import com.zhiche.lisa.core.utils.Account.JwtAccountVO;
import com.zhiche.lisa.core.utils.HttpClientUtil;
import com.zhiche.lisa.core.utils.RegexUtil;
import com.zhiche.lisa.core.utils.redislog.RedisLogUtil;
import com.zhiche.lisa.lspm.config.LspmProperties;
import com.zhiche.lisa.lspm.dao.mapper.driver.DriverMapper;
import com.zhiche.lisa.lspm.dao.model.carrier.CarrierInfo;
import com.zhiche.lisa.lspm.dao.model.carrier.CarrierLicense;
import com.zhiche.lisa.lspm.dao.model.carrier.CarrierTrailerBind;
import com.zhiche.lisa.lspm.dao.model.carrier.CarrierTrailerBindLog;
import com.zhiche.lisa.lspm.dao.model.carrier.bo.CarAndDriverInfoLineBO;
import com.zhiche.lisa.lspm.dao.model.carrier.bo.CarrierDriverBO;
import com.zhiche.lisa.lspm.dao.model.carrier.bo.CarrierInfoBO;
import com.zhiche.lisa.lspm.dao.model.driver.*;
import com.zhiche.lisa.lspm.dao.model.driver.bo.*;
import com.zhiche.lisa.lspm.dao.model.fleet.Fleet;
import com.zhiche.lisa.lspm.dao.model.fleet.FleetBind;
import com.zhiche.lisa.lspm.dao.model.lsp.LspInfo;
import com.zhiche.lisa.lspm.dao.model.lsp.LspLicense;
import com.zhiche.lisa.lspm.dao.model.sys.User;
import com.zhiche.lisa.lspm.dao.model.trailer.TrailerInfo;
import com.zhiche.lisa.lspm.dao.model.trailer.bo.TrailerInfoBO;
import com.zhiche.lisa.lspm.dto.*;
import com.zhiche.lisa.lspm.service.carrier.ICarrierInfoService;
import com.zhiche.lisa.lspm.service.carrier.ICarrierLicenseService;
import com.zhiche.lisa.lspm.service.carrier.ICarrierTrailerBindLogService;
import com.zhiche.lisa.lspm.service.carrier.ICarrierTrailerBindService;
import com.zhiche.lisa.lspm.service.driver.*;
import com.zhiche.lisa.lspm.service.fleet.IFleetBindService;
import com.zhiche.lisa.lspm.service.fleet.IFleetService;
import com.zhiche.lisa.lspm.service.lsp.LspInfoService;
import com.zhiche.lisa.lspm.service.lsp.LspLicenseService;
import com.zhiche.lisa.lspm.service.sys.IUserService;
import com.zhiche.lisa.lspm.service.trailer.TrailerInfoService;
import com.zhiche.lisa.lspm.service.upload.UploadService;
import com.zhiche.lisa.lspm.service.utils.IntegrationUtil;
import com.zhiche.lisa.lspm.service.utils.MdmUtil;
import com.zhiche.lisa.lspm.service.utils.UaaUtil;
import com.zhiche.lisa.lspm.vo.common.*;
import com.zhiche.lisa.lspm.vo.driver.*;
import com.zhiche.lisa.lspm.vo.fleet.FleetBindVO;
import com.zhiche.lisa.lspm.vo.vehicle.CarAndDriverInfoLineVO;
import com.zhiche.lisa.lspm.vo.vehicle.WeChatVehicle;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.joda.time.DateTime;
import org.joda.time.Period;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.jms.Destination;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;


@Service
public class DriverServiceImpl extends ServiceImpl<DriverMapper, Driver> implements IDriverService {

	private static final Logger LOGGER = LoggerFactory.getLogger(IDriverService.class);

	@Autowired
	private IDriverLicenseService driverLicenseService;
	@Autowired
	private IDriverBankAccountService driverBankAccountService;
	@Autowired
	private IDriverLicenseAttachService driverLicenseAttachService;
	@Autowired
	private ICarrierInfoService carrierInfoService;
	@Autowired
	private TrailerInfoService trailerInfoService;
	@Autowired
	private IDriverAuditLogService iDriverAuditLogService;
	@Autowired
	private IntegrationUtil integrationUtil;
	@Autowired
	private LspInfoService lspInfoService;
	@Autowired
	private IDriverCarrierBindService driverCarrierBindService;
	@Autowired
	private UploadService uploadService;
	@Autowired
	private MdmUtil mdmUtil;
	@Autowired
	private UaaUtil uaaUtil;
	@Autowired
	private IDriverCreateLogService iDriverCreateLogService;
	@Autowired
	private ICarrierTrailerBindService carrierTrailerBindService;
	@Autowired
	private ICarrierTrailerBindLogService carrierTrailerBindLogService;
	@Autowired
	private IDriverCarrierBindLogService driverCarrierBindLogService;
	@Autowired
	private IFleetBindService fleetBindService;
	@Autowired
	private LspLicenseService lspLicenseService;
	@Autowired
	private IFleetService fleetService;
	@Autowired
	private LspmProperties properties;
	@Autowired
	private IUserService iUserService;
	@Autowired
	private JmsTemplate jmsTemplate;
	@Autowired
	private ICarrierLicenseService licenseService;
	@Autowired
	private IDriverCheckinService driverCheckinService;

	@Value("${mqName.registDriver}")
	private String mqNameRegistDriver;

	@Value("${lisa.lspm.registerDriverUrl}")
	private String registerDriverUrl;

	@Value("${uaa.getAccountDredgeUrl}")
	private String getAccountDredgeUrl;

	@Value("${uaa.socketTimeout}")
	private Integer socketTimeout;

	@Value("${uaa.accountGetAccountuRrl}")
	private String accountGetAccountuRrl;

	@Value("${lisa.tms.driverWaybillUrl}")
	private String driverWaybillUrl;

	@Value("${uaa.updateTenantOfAccountUrl}")
	private String updateTenantOfAccountUrl;

	@Value("${uaa.url}")
	private String uaaUrl;

	@Value("${integration.url}")
	private String integrationUrl;

	@Value("${integration.driverPushErpUrl}")
	private String driverPushErpUrl;

	@Value("${logRedis.isTest}")
	private boolean isTest;
	@Override
	public Page<DriverLineVO> driverLine(Page<DriverLineBO> page) {
		Wrapper<DriverLineBO> ew = driverLineWhere(page);
		Page<DriverLineVO> pageVo = new Page<>();
		List<DriverLineVO> list = baseMapper.driverLine(page, ew);
		BeanUtils.copyProperties(page, pageVo);
		pageVo.setRecords(list);
		return pageVo;
	}

	@Override
	public Page<DriverLineVO> authedDriverLine(Page<DriverLineBO> page) {
		Wrapper<DriverLineBO> ew = driverLineWhere(page);
		Page<DriverLineVO> pageVo = new Page<>();
		List<DriverLineVO> list = baseMapper.authedDriverLine(page, ew);
		BeanUtils.copyProperties(page, pageVo);
		pageVo.setRecords(list);
		return pageVo;
	}

	@Override
	public Page<CarAndDriverInfoLineVO> carAndDriverInfoLine(Page<CarAndDriverInfoLineBO> page) {
		Wrapper<CarAndDriverInfoLineBO> ew = new EntityWrapper<CarAndDriverInfoLineBO>();
		Page<CarAndDriverInfoLineVO> pageVo = new Page<>();
		// 承运商 id
		if (page.getCondition() != null
				&& Objects.nonNull(page.getCondition().get("lspId"))) {
			ew.eq("lsp_id", page.getCondition().get("lspId").toString().trim());
		}
		// 车牌号 id
		if (page.getCondition() != null
				&& Objects.nonNull(page.getCondition().get("plate"))) {
			ew.like("plate", page.getCondition().get("plate").toString().trim());
		}
		List<CarAndDriverInfoLineVO> list = baseMapper.carAndDriverInfoLine(page, ew);
		BeanUtils.copyProperties(page, pageVo);
		pageVo.setRecords(list);
		return pageVo;
	}

	private EntityWrapper<DriverLineBO> driverLineWhere(Page<DriverLineBO> page) {
		EntityWrapper<DriverLineBO> ew = new EntityWrapper<>();
		if (page.getCondition() != null
				&& !StringUtils.isEmpty(page.getCondition().get("lspId"))) {
			ew.eq("lsp_id", page.getCondition().get("lspId").toString().trim());
		}
		if (page.getCondition() != null
				&& Objects.nonNull(page.getCondition().get("tenantId"))) {
			ew.eq("tenant_id", page.getCondition().get("tenantId").toString().trim());
		}
		if (page.getCondition() != null
				&& !StringUtils.isEmpty(page.getCondition().get("canDel"))) {
			ew.eq("is_delete", page.getCondition().get("canDel").toString().trim());
		} else {
			ew.eq("is_delete", 0);
		}
		// 姓名或者身份证号
		if (page.getCondition() != null
				&& !StringUtils.isEmpty(page.getCondition().get("name"))) {
			ew.like("name", page.getCondition().get("name").toString().trim()).orNew().like("license_id", page.getCondition().get("name").toString().trim());
		}
		// 司机手机号
		if (page.getCondition() != null
				&& !StringUtils.isEmpty(page.getCondition().get("mobile"))) {
			ew.like("mobile", page.getCondition().get("mobile").toString().trim());
		}
		ew.orderBy("gmt_create", false);
		return ew;
	}


	@Transactional
	@Override
	public void addDriver(ModifyDriverBO modifyDriverBO, String authorization) throws BaseException {

		try {
			Driver driver = new Driver();

			if (modifyDriverBO.getBusinessSite() != null
					&& modifyDriverBO.getBusinessSite().length() > 500) {
				throw new BaseException("业务覆盖城市太长");
			}
			if (Objects.isNull(modifyDriverBO.getTenantId())) throw new BaseException("请选择所属公司");
			if (!Strings.isNullOrEmpty(modifyDriverBO.getName()))
				if (!RegexUtil.check(RegexUtil.REGEX_UNICODECHAR, modifyDriverBO.getName()))
					throw new BaseException("车主姓名不合法");
			checkModifyData(modifyDriverBO, "insert");
			// 添加司机基础信息
			Long lspId = lspInfoService.getLspIdByTenantId(modifyDriverBO.getTenantId());
			if (!Objects.isNull(lspId)) modifyDriverBO.setLspId(lspId);

			BeanUtils.copyProperties(modifyDriverBO, driver);

			RestfulResponse<Account> rest = uaaUtil.signup("", driver.getMobile(), "123456", authorization, modifyDriverBO.getTenantId());
			if (CommonEnum.SUCCESS.getCode().equals(rest.getCode())) {
				driver.setAccountId(Long.valueOf(rest.getData().getId()));
			} else {
				throw new BaseException(rest.getMessage());
			}

			driver.setStatus(StatusEnum.DISCONTINUAT.getCode());
			driver.setAuthStatus(AuthStatusEnum.UNAUTHORIZED.getCode());
			driver.setCreateFrom(SourceEnum.LSPM.getText());
			this.insert(driver);
			// 添加司机证照

			List<ModifyDriverLicenseBO> modifyDriverLicenseBOList = modifyDriverBO.getModifyDriverLicenseBOList();
			for (ModifyDriverLicenseBO modifyDriverLicenseBO : modifyDriverLicenseBOList) {
				DriverLicense driverLicense = new DriverLicense();
				BeanUtils.copyProperties(modifyDriverLicenseBO, driverLicense);
				driverLicense.setDriverId(driver.getId());
				driverLicenseService.insert(driverLicense);
			}

			// 添加银行账号信息
			List<DriverBankAccount> driverBankAccountList = modifyDriverBO.getDriverBankAccountList();
			for (DriverBankAccount driverBankAccount : driverBankAccountList) {
				driverBankAccount.setDriverId(driver.getId());
			}
			if (!CollectionUtils.isEmpty(driverBankAccountList)) {
				driverBankAccountService.insertBatch(driverBankAccountList);
			}
		} catch (BaseException e) {
			throw e;
		} catch (Exception ex) {
			throw new BaseException(-1, "操作异常请重试");
		}

	}

	private DriverLicense getLicenseByIdOrType(ModifyDriverLicenseBO modifyDriverLicenseBO, Long driverId) {
		DriverLicense license = new DriverLicense();
		if (Objects.isNull(modifyDriverLicenseBO.getId())) {
			EntityWrapper<DriverLicense> ew = new EntityWrapper<>();
			ew.eq("driver_id", driverId);
			ew.eq("license_type_id", modifyDriverLicenseBO.getLicenseTypeId());
			List<DriverLicense> driverLicenses = driverLicenseService.selectList(ew);
			if (!CollectionUtils.isEmpty(driverLicenses)) {
				license = driverLicenses.get(0);
			}
		} else {
			EntityWrapper<DriverLicense> ew = new EntityWrapper<>();
			ew.eq("id", modifyDriverLicenseBO.getId());
			List<DriverLicense> driverLicenses = driverLicenseService.selectList(ew);
			if (!CollectionUtils.isEmpty(driverLicenses)) {
				license = driverLicenses.get(0);
			}
		}
		return license;
	}

	@Override
	public boolean updateLicense(ModifyDriverBO modifyDriverBO) {
		if (Objects.isNull(modifyDriverBO.getId())) throw new BaseException("未绑定承运商");
		List<ModifyDriverLicenseBO> toCarrierLicenseList = modifyDriverBO.getModifyDriverLicenseBOList();
		for (ModifyDriverLicenseBO modifyDriverLicenseBO : toCarrierLicenseList) {
			DriverLicense license = new DriverLicense();
			BeanUtils.copyProperties(modifyDriverLicenseBO, license);
			license.setId(getLicenseByIdOrType(modifyDriverLicenseBO, modifyDriverBO.getId()).getId());
			if (Objects.isNull(license.getId())) {
				license.setDriverId(modifyDriverBO.getId());
				driverLicenseService.insert(license);
				// 添加承运商证照附件
//                List<DriverLicenseAttach> driverLicenseAttaches = modifyDriverLicenseBO.getDriverLicenseAttachList();
				DriverLicenseAttach driverLicenseAttache = modifyDriverLicenseBO.getDriverLicenseAttachList().get(0);
				driverLicenseAttache.setDriverId(modifyDriverBO.getId());
				driverLicenseAttache.setLicenseId(license.getId());
				driverLicenseAttachService.insert(driverLicenseAttache);
				return true;
			} else {
				for (DriverLicenseAttach driverLicenseAttach :
						modifyDriverLicenseBO.getDriverLicenseAttachList()) {
					//删除原有附件
					EntityWrapper<DriverLicenseAttach> ewAttach = new EntityWrapper<>();
					ewAttach.eq("driver_id", modifyDriverBO.getId());
					ewAttach.eq("license_id", license.getId());
					ewAttach.eq("attach_type", driverLicenseAttach.getAttachType());
					//获取该司机对应证照的现有的附件信息
					DriverLicenseAttach licenseAttach = driverLicenseAttachService.selectOne(ewAttach);
					//若存在附件
					if (Objects.nonNull(licenseAttach)) {
						//和本次上传的附件不一样，软删之后判断是否已经存在状态为软删除的附件，存在则删除现在的，在新增，不存在则改变状态，一样的话，直接跳过本次新增
						if (!driverLicenseAttach.getAttachKey().equals(licenseAttach.getAttachKey())) {
							driverLicenseAttachService.updateOldAttachDeleteState(licenseAttach);
						} else {
							continue;
						}
					}
					//修改附件对应信息，写入库
					driverLicenseAttach.setDriverId(modifyDriverBO.getId());
					driverLicenseAttach.setLicenseId(license.getId());
					driverLicenseAttachService.insert(driverLicenseAttach);
					return true;
				}
			}

		}
		return false;
	}

	@Override
	public void deleteLicense(ModifyDriverLicenseBO modifyDriverLicenseBO) {
		for (DriverLicenseAttach driverLicenseAttach :
				modifyDriverLicenseBO.getDriverLicenseAttachList()) {
			if (Objects.isNull(driverLicenseAttach.getId())) {
				EntityWrapper<DriverLicense> ew = new EntityWrapper<>();
				ew.eq("license_type_id", modifyDriverLicenseBO.getLicenseTypeId());
				ew.eq("driver_id", modifyDriverLicenseBO.getDriverId());
				List<DriverLicense> carrierLicenses = driverLicenseService.selectList(ew);
				if (CollectionUtils.isEmpty(carrierLicenses)) throw new BaseException("未查找到匹配删除项");
				EntityWrapper<DriverLicenseAttach> ewAttach = new EntityWrapper<>();
				DriverLicense carrierLicense = carrierLicenses.get(0);
				ewAttach.eq("driver_id", modifyDriverLicenseBO.getDriverId());
				ewAttach.eq("driver_license_id", carrierLicense.getId());
				ewAttach.eq("attach_type", driverLicenseAttach.getAttachType());
//                ewAttach.eq("is_delete", "0");
//                driverLicenseAttachService.updateDeleteState(ewAttach);
				DriverLicenseAttach licenseAttach = driverLicenseAttachService.selectOne(ewAttach);
				driverLicenseAttachService.updateOldAttachDeleteState(licenseAttach);
			} else {
				EntityWrapper<DriverLicenseAttach> ewAttach = new EntityWrapper<>();
				ewAttach.eq("id", driverLicenseAttach.getId());
//                ewAttach.eq("is_delete", "0");
//                driverLicenseAttachService.updateDeleteState(ewAttach);
				DriverLicenseAttach licenseAttach = driverLicenseAttachService.selectOne(ewAttach);
				driverLicenseAttachService.updateOldAttachDeleteState(licenseAttach);
			}
		}
	}

	@Override
	public ModifyDriverBO findModifyInfo(Long id) {

		if (id == null)
			throw new BaseException(-1, "司机ID为空");

		// 查询编辑司机信息
		Driver driver = this.selectById(id);
		if (driver == null)
			throw new BaseException(-1, "司机信息不存在");

		ModifyDriverBO modifyDriverBO = new ModifyDriverBO();

		BeanUtils.copyProperties(driver, modifyDriverBO);

		// 查询所属承运商
		if (modifyDriverBO.getLspId() != null) {
			LspInfo lspInfo = lspInfoService.selectById(modifyDriverBO.getLspId());
			if (lspInfo != null) {
				modifyDriverBO.setLspName(lspInfo.getName());
			}
		}

		Boolean isHavaAttach = false;

		// 查找司机的证照信息
		Wrapper<DriverLicense> licenseEntity = new EntityWrapper<>();
		licenseEntity.eq("driver_id", id);
		List<DriverLicense> licenseList = driverLicenseService.selectList(licenseEntity);
		if (!CollectionUtils.isEmpty(licenseList)) {
			List<ModifyDriverLicenseBO> modifyDriverLicenseBOList = new ArrayList<>();
			for (DriverLicense license : licenseList) {
				ModifyDriverLicenseBO modifyDriverLicenseBO = new ModifyDriverLicenseBO();
				BeanUtils.copyProperties(license, modifyDriverLicenseBO);

				// 查找证照的附件信息
				Wrapper<DriverLicenseAttach> licenseAttachEntity = new EntityWrapper<>();
				licenseAttachEntity.where("driver_license_id = {0}", license.getId()).and("driver_id ={0}", id);
				List<DriverLicenseAttach> driverLicenseAttachList = driverLicenseAttachService.selectList(licenseAttachEntity);
				if (!CollectionUtils.isEmpty(driverLicenseAttachList)) {
					modifyDriverLicenseBO.setDriverLicenseAttachList(driverLicenseAttachList);
					isHavaAttach = true;
				}

				modifyDriverLicenseBO.setStatus(getValidStatus(license, isHavaAttach));
				modifyDriverLicenseBOList.add(modifyDriverLicenseBO);
			}
			if (!CollectionUtils.isEmpty(modifyDriverLicenseBOList)) {
				modifyDriverBO.setModifyDriverLicenseBOList(modifyDriverLicenseBOList);
			}
		}

		//获取银行卡
		Wrapper<DriverBankAccount> ew = new EntityWrapper<>();
		ew.eq("driver_id", id);
		List<DriverBankAccount> bankList = driverBankAccountService.selectList(ew);
		if (!CollectionUtils.isEmpty(bankList)) {
			modifyDriverBO.setDriverBankAccountList(bankList);
		}
		return modifyDriverBO;
	}

	public void checkModifyData(ModifyDriverBO modifyDriverBO, String operate) {

		if (modifyDriverBO == null || StringUtils.isEmpty(operate))
			return;
		if (operate.equals("modify")) {
			if (modifyDriverBO.getId() == null)
				return;
			Wrapper<Driver> mobileDriverEntity = new EntityWrapper<>();
			mobileDriverEntity.eq("mobile", modifyDriverBO.getMobile().trim()).ne("id", modifyDriverBO.getId());
			List<Driver> mobileDriverList = baseMapper.selectDriverNoTenant(mobileDriverEntity);
			if (!CollectionUtils.isEmpty(mobileDriverList)) {
				throw new BaseException(DriverExceptionEnum.DRIVER_MOBLIE_EXIST.getCode(), "该手机号已被使用");
			}
		}
		if (Objects.isNull(modifyDriverBO))
			return;
		if (operate.equals("insert")) {
			Wrapper<Driver> plateCarrierEntity = new EntityWrapper<>();
			plateCarrierEntity.eq("mobile", modifyDriverBO.getMobile().trim());
			List<Driver> plateCarrierList = baseMapper.selectDriverNoTenant(plateCarrierEntity);
			if (!CollectionUtils.isEmpty(plateCarrierList)) {
				throw new BaseException(DriverExceptionEnum.DRIVER_MOBLIE_EXIST.getCode(), "该手机号已被使用");
			}
		}
	}

	@Transactional
	@Override
	public void modifyDriver(ModifyDriverBO modifyDriverBO) throws BaseException {

		try {
			if (modifyDriverBO.getBusinessSite() != null
					&& modifyDriverBO.getBusinessSite().length() > 500) {
				throw new BaseException("业务覆盖城市太长");
			}
			if (!Strings.isNullOrEmpty(modifyDriverBO.getName()))
				if (!RegexUtil.check(RegexUtil.REGEX_UNICODECHAR, modifyDriverBO.getName()))
					throw new BaseException("车主姓名不合法");
			checkModifyData(modifyDriverBO, "modify");
			// 更新司机基础信息
			Driver driver = new Driver();
			BeanUtils.copyProperties(modifyDriverBO, driver);
			Long lspId = lspInfoService.getLspIdByTenantId(modifyDriverBO.getTenantId());
			driver.setLspId(lspId);
			Integer authStatus = driver.getAuthStatus();
			if (authStatus == AuthStatusEnum.CERTIFICATION.getCode()) {
				throw new BaseException(-1, "该司机已经认证，请取消认证后再进行修改");
			}
			this.updateById(driver);

			// 查询司机下的证照
			Wrapper<DriverLicense> driverLicenseEntity = new EntityWrapper<>();
			driverLicenseEntity.eq("driver_id", driver.getId());
			List<DriverLicense> selectDriverLicenseList = driverLicenseService.selectList(driverLicenseEntity);
			// 前端传送的证照
			List<ModifyDriverLicenseBO> toDriverLicenseList = modifyDriverBO.getModifyDriverLicenseBOList();

			if (CollectionUtils.isEmpty(selectDriverLicenseList)) {
				//原来没有证照
				toDriverLicenseList.forEach(modifyDriverLicenseBO -> {
					DriverLicense driverLicense = new DriverLicense();
					BeanUtils.copyProperties(modifyDriverLicenseBO, driverLicense);
					driverLicense.setDriverId(driver.getId());
					driverLicenseService.insert(driverLicense);
				});
			} else {
				toDriverLicenseList.forEach(modifyDriverLicenseBO -> {
					DriverLicense license = new DriverLicense();
					BeanUtils.copyProperties(modifyDriverLicenseBO, license);
					license.setId(getLicenseByIdOrType(modifyDriverLicenseBO, modifyDriverBO.getId()).getId());
					if (Objects.isNull(license.getId())) {
						//新增
						license.setDriverId(driver.getId());
						driverLicenseService.insert(license);
					} else {
						//更新
						driverLicenseService.updateById(license);
					}
				});
			}
			// 前端传送的银行账号信息
			List<DriverBankAccount> toDriverBankAccountList = modifyDriverBO.getDriverBankAccountList();
			// 前端添加的银行账号信息
			List<DriverBankAccount> addDriverBankAccountList = new ArrayList<>();
			// 更新司机银行账号信息
			for (DriverBankAccount toDriverBankAccount : toDriverBankAccountList) {
				if (toDriverBankAccount.getId() == null) {
					toDriverBankAccount.setDriverId(driver.getId());
					addDriverBankAccountList.add(toDriverBankAccount);
				} else {
					driverBankAccountService.updateById(toDriverBankAccount);
				}
			}
			if (!CollectionUtils.isEmpty(addDriverBankAccountList)) {
				// 批量添加银行账号信息
				driverBankAccountService.insertBatch(addDriverBankAccountList);
			}

		} catch (BaseException e) {
			throw e;
		} catch (Exception ex) {
			throw new BaseException(-1, "操作异常请重试");
		}

	}

	@Override
	public Page<DriverLineVO> getDriverByLsp(Page<DriverLineVO> page) {
		if (Objects.isNull(page.getCondition().get("lspId"))) throw new BaseException("未获取到对应承运商");
		EntityWrapper<DriverLineBO> ew = new EntityWrapper<>();
		ew.eq("lsp_id", page.getCondition().get("lspId"));
		if (Objects.nonNull(page.getCondition().get("phone"))) {
			ew.like("mobile", page.getCondition().get("phone").toString());
		}
		if (!Objects.isNull(page.getCondition().get("isAuth"))) {
			if ("1".equals(page.getCondition().get("isAuth").toString())) {
				ew.eq("auth_status", AuthStatusEnum.CERTIFICATION.getCode());
			} else {
				ew.eq("auth_status", AuthStatusEnum.UNAUTHORIZED.getCode());
			}
		}
		ew.eq("is_delete", TableStatusEnum.STATUS_0.getCode());
		Page<DriverLineBO> page1 = new Page<>(page.getCurrent(), page.getSize());
		List<DriverLineVO> driverLineVOS = baseMapper.driverLine(page1, ew);
		BeanUtils.copyProperties(page1, page);
		page.setRecords(driverLineVOS);
		return page;
	}

	@Override
	public List<String> discontinuatDriver(Long[] driverIds, String token) throws BaseException {

		if (ArrayUtils.isEmpty(driverIds)) {
			throw new BaseException("司机ID为空");
		}
		List<String> msgs = new ArrayList<>();
		for (Long driverId : driverIds) {
			Driver driver = this.selectById(driverId);
			if (driver.getStatus().equals(StatusEnum.DISCONTINUAT.getCode())) {
				msgs.add("司机:" + driver.getName() + ":已经停用，无需再次停用");
				continue;
			}
			List<Long> listIds = new ArrayList<>();
			listIds.add(driverId);
			baseMapper.batchUpdateStatus(StatusEnum.DISCONTINUAT.getCode(), listIds);
			//uaaUtil.lockAccount(driver.getAccountId().toString(), token);

		}
		return msgs;
	}

	@Override
	public List<String> enableDriver(Long[] driverIds, String token) throws BaseException {
		if (ArrayUtils.isEmpty(driverIds)) {
			throw new BaseException("司机ID为空");
		}
		List<String> msgs = new ArrayList<>();
		for (Long driverId : driverIds) {
			Driver driver = this.selectById(driverId);
			if (driver.getStatus().equals(StatusEnum.ENABLE.getCode())) {
				msgs.add("司机:" + driver.getName() + ":已经启用，无需再次启用");
				continue;
			}
			List<Long> listIds = new ArrayList<>();
			listIds.add(driverId);
			baseMapper.batchUpdateStatus(StatusEnum.ENABLE.getCode(), listIds);
			//uaaUtil.unlockAccount(driver.getAccountId().toString(), token);
		}
		return msgs;
	}


	@Override
	public void batchUpdateStatusByLspId(Integer authStatus, Integer status, List<Long> lspIdList) {
		baseMapper.batchUpdateStatusByLspId(authStatus, status, lspIdList);
	}

	@Transactional
	public void driverAuth(Long driverId, String authorization) throws BaseException {
		Wrapper<DriverLineBO> driverEW = new EntityWrapper<DriverLineBO>()
				.eq("id", driverId)
				.orderBy("id", false);
		List<DriverLineVO> driverLineVOs = baseMapper.driverLine(new Page<>(), driverEW);
		DriverLineVO driver = driverLineVOs.get(0);
		if (Objects.isNull(driver)) {
			throw new BaseException("司机不存在");
		}
		if (driver.getAuthStatus().equals(AuthStatusEnum.CERTIFICATION.getCode())) {
			throw new BaseException("司机:" + driver.getName() + ":" + "已经是认证状态，无需重复进行认证");
		}
		//自有车队司机(取消认证再修改)信息推ERP
		driverToOtm(driverId);

		authDriverToERP(authorization, driver.getId());

		//更新认证
		Driver authDriver = new Driver();
		authDriver.setId(driverId);
		authDriver.setAuthStatus(Integer.valueOf(TableStatusEnum.STATUS_1.getCode()));
		authDriver.setStatus(Integer.valueOf(TableStatusEnum.STATUS_1.getCode()));
		baseMapper.updateById(authDriver);

		//认证日志
		JwtAccountVO jwtAccountVO = AccountUtil.getAccountInfoFromSecurityContext();
		DriverAuditLog driverAuditLog = new DriverAuditLog();
		driverAuditLog.setDriverId(driverId);
		driverAuditLog.setAuditResult(1);
		if (Objects.nonNull(jwtAccountVO)) {
			driverAuditLog.setTenantId(Long.parseLong(jwtAccountVO.getTenantId()));
			driverAuditLog.setCreator(jwtAccountVO.getAccountId());
		}
		iDriverAuditLogService.insert(driverAuditLog);
	}

	@Override
	public void authDriverToERP(String authorization, Long driverId) {
		if (TableStatusEnum.STATUS_Y.getCode().equals(properties.getPushDataToERP())) {
			Driver driver = baseMapper.selectById(driverId);
			if (driver != null) {
				//推送司机
				DriverToErpDTO driverToErpDTO = new DriverToErpDTO();
				driverToErpDTO.setId(driver.getId());
				driverToErpDTO.setDriverName(driver.getName());
				driverToErpDTO.setDriverMobile(driver.getMobile());
				driverToErpDTO.setLspId(String.valueOf(driver.getLspId()));
				// 拿取承运商名
				LspInfo lspInfo = lspInfoService.selectById(driver.getLspId());
				if (lspInfo != null) {
					driverToErpDTO.setLspName(lspInfo.getName());
				}
				//车队绑定信息
				EntityWrapper<FleetBind> ew = new EntityWrapper<>();
				ew.eq("resource_id", driver.getId())
						.eq("resource_type", TableStatusEnum.STATUS_03.getCode())
						.orderBy("id", false);
				List<FleetBind> binds = fleetBindService.selectListNoTenant(ew);
				List<NameValuePair> headNamePairs = Lists.newArrayList();
				headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
				if (!CollectionUtils.isEmpty(binds)) {
					FleetBind fleetBind = binds.get(0);
					Fleet fleet = fleetService.selectByIdNoTenant(fleetBind.getFleetId());
					driverToErpDTO.setFleetId(String.valueOf(fleet.getId()));
					driverToErpDTO.setFleetName(fleet.getFleetName());
					Long fleetTypeId = fleet.getFleetTypeId();
					if (fleetTypeId != null
							&& TableStatusEnum.STATUS_2.getCode().equals(String.valueOf(fleetTypeId))) {
						driverToErpDTO.setProperty(TableStatusEnum.STATUS_3.getCode());
					} else if (fleetTypeId != null
							&& TableStatusEnum.STATUS_1.getCode().equals(String.valueOf(fleetTypeId))) {
						driverToErpDTO.setProperty(TableStatusEnum.STATUS_1.getCode());
					} else if (fleetTypeId != null) {
						driverToErpDTO.setProperty(TableStatusEnum.STATUS_2.getCode());
					}
				} else {
					// 新车队规则为空查老车队与牵引车绑定车队规则
					DriverToErpVO driverVO = baseMapper.driverToErpVO(driverId);
					if (driverVO != null) {
						driverToErpDTO.setFleetId(String.valueOf(driverVO.getNewFleetId()));
						driverToErpDTO.setFleetName(String.valueOf(driverVO.getFleetName()));
						String fleetTypeId = String.valueOf(driverVO.getFleetTypeId());
						if (TableStatusEnum.STATUS_2.getCode().equals(fleetTypeId)) {
							driverToErpDTO.setProperty(TableStatusEnum.STATUS_3.getCode());
						} else if (TableStatusEnum.STATUS_1.getCode().equals(fleetTypeId)) {
							driverToErpDTO.setProperty(fleetTypeId);
						} else if (!StringUtils.isEmpty(fleetTypeId)) {
							driverToErpDTO.setProperty(TableStatusEnum.STATUS_2.getCode());
						}
					}
				}
				CarrierInfoBO infoBO = carrierInfoService.selectByDriverId(driverId);
				if (infoBO != null) {
					driverToErpDTO.setPlate(infoBO.getPlate());
					driverToErpDTO.setCarrierId(String.valueOf(infoBO.getId()));
				}
				EntityWrapper<DriverLicense> licenseEW = new EntityWrapper<>();
				licenseEW.eq("driver_id", driver.getId())
						.eq("license_type_id", TableStatusEnum.STATUS_1.getCode())
						.orderBy("id", false);
				DriverLicense driverLicense = driverLicenseService.selectOneNoTenant(licenseEW);
				if (Objects.nonNull(driverLicense)) {
					driverToErpDTO.setLicenseId(driverLicense.getLicenseId());
				}
				String paramJson = JSONObject.toJSONString(driverToErpDTO);
				new Thread(() -> {
					try {
						LOGGER.info("driverInfoToErp info url:{},params:{} ", integrationUrl + driverPushErpUrl, paramJson);
						RedisLogUtil.addSysLogs(SystemEnum.LSPM.getCode(),SystemEnum.INTEGRATION.getCode(),"driver"+driverToErpDTO.getId(), JSON.toJSONString(driverToErpDTO),"/erp-api/driverPushErp",1,1,null,isTest);

						String driverResult = HttpClientUtil.postJson(integrationUrl + driverPushErpUrl, headNamePairs, paramJson, socketTimeout);
						LOGGER.info("driverInfoToErp result {} ", driverResult);
					} catch (Exception e) {
						LOGGER.error("driverInfoToErp url:{},params:{} 连接超时:{}", integrationUrl + driverPushErpUrl, paramJson, e);
					}
				}).start();
			}
		}
	}


	@Override
	public List<String> batchUpdateAuthStatusByIds(Long[] driverIds, String authorization) throws BaseException {
		if (ArrayUtils.isEmpty(driverIds)) throw new BaseException("司机ID为空");
		List<String> errorMsg = new ArrayList<>();

		for (Long driverId : driverIds) {
			try {
				driverAuth(driverId, authorization);
			} catch (BaseException e) {
				errorMsg.add(e.getMessage());
			} catch (Exception e) {
				errorMsg.add(e.getMessage());
				LOGGER.error(e.getMessage());
			}
		}
		return errorMsg;
	}

    /*private boolean licenseValid(Long carrierId) throws BaseException {

        EntityWrapper<DriverLicense> ew = new EntityWrapper<>();
        ew.eq("driver_id", carrierId);
        List<DriverLicense> driverLicenses = driverLicenseService.selectList(ew);
        List<LicenseTypeVo> licenseTypes = mdmUtil.listLicenseTypeBySubject("01");
        for (DriverLicense license : driverLicenses) {
            LicenseTypeVo licenseType = getLicenseType(license.getLicenseTypeId(), licenseTypes);
            if (Objects.nonNull(licenseType)) {
                if (StringUtils.isEmpty(license.getLicenseId())) throw new BaseException(
                        licenseType.getTypeValue() + "编码为空");
//                if (Objects.isNull(license.getGmtReg())) throw new BaseException(licenseType.getTypeValue()
//                        + "生效日期为空");
//                if (!licenseType.getIsPerm().equals(1) && Objects.isNull(license.getGmtOverdue())) {
//                    throw new BaseException(licenseType.getTypeValue() + "失效日期为空！");
//                }
                Wrapper<DriverLicenseAttach> ewAttach = new EntityWrapper<>();
                ewAttach.eq("driver_license_id", license.getId()).and().eq("driver_id", license.getDriverId());
                if (driverLicenseAttachService.selectCount(ewAttach) == 0) {
                    throw new BaseException(licenseType.getTypeValue() + "附件为空！");
                }
            } else {
                throw new BaseException("司机证照类型有误");
            }

        }
        return true;
    }*/

    /*private LicenseTypeVo getLicenseType(Long licenseTypeId, List<LicenseTypeVo> licenseTypes) {
        LicenseTypeVo newLicenseType = null;
        Optional<LicenseTypeVo> optional = licenseTypes.stream().filter(licenseType -> licenseType.getId().equals(licenseTypeId)).findFirst();
        if (optional.isPresent()) {
            newLicenseType = optional.get();
        }
        return newLicenseType;
    }*/

	@Transactional
	@Override
	public void batchUpdateCancelAuthStatusByIds(Long[] driverIds) throws BaseException {
		try {
			if (ArrayUtils.isEmpty(driverIds)) {
				throw new BaseException("司机的ID为空");
			}
			List<Long> idList = Arrays.asList(driverIds);
			List<DriverDTO> driverDTOS = Lists.newArrayList();
			idList.forEach(driverId -> {
//                Driver driver = this.selectById(driverId);
				List<DriverLineVO> driverLineVOs = baseMapper.driverLine(new Page<>(), new EntityWrapper<DriverLineBO>().eq("id", driverId));
				DriverLineVO driver = driverLineVOs.get(0);
				if (!Objects.isNull(driver)) {
					if (driver.getAuthStatus() == AuthStatusEnum.UNAUTHORIZED.getCode()) {
						throw new BaseException("司机：" + driver.getName() + "已经取消认证，无需重复取消认证");
					}
					DriverDTO driverDTO = new DriverDTO();
					BeanUtils.copyProperties(driver, driverDTO);
					driverDTOS.add(driverDTO);
				}
			});
			baseMapper.batchUpdateAuthStatusByIds(AuthStatusEnum.UNAUTHORIZED.getCode(), StatusEnum.DISCONTINUAT.getCode(), idList);
			if (IntegrationEnum.EXPORT.getCode().equals(IntegrationUtil.getIntegrationToOtm())) {
				for (DriverDTO driverDTO :
						driverDTOS) {
					driverDTO.setIsActive("N");
					driverDTO.setServiceType(integrationUtil.getServiceType(driverDTO.getServiceType()));
					integrationUtil.exportDriverToOTM(driverDTO);
				}
			}
			//写入日志表
			iDriverAuditLogService.batchInsertLog(idList, AuthStatusEnum.UNAUTHORIZED.getCode());
		} catch (Exception ex) {
			throw new BaseException(-1, ex.getMessage());
		}
	}

	@Override
	public List<Long> selectIdByLspIds(List<Long> lspIdList) {
		return baseMapper.selectIdByLspIds(lspIdList);
	}

	@Override
	public void batchUpdateAuthStatusByIds(Integer authStatus, Integer status, List<Long> idList) {
		baseMapper.batchUpdateAuthStatusByIds(authStatus, status, idList);
	}

	@Override
	public Page<DriverCarrierBO> queryPageDriverCarrier(Page<DriverCarrierBO> page, String authorization) {
		Map<String, Object> condition = page.getCondition();
		Wrapper<DriverCarrierBO> ew = buildDriverCarCondition(condition);
		baseMapper.updateSQLMode();
		List<DriverCarrierBO> driverCarrierBOS = baseMapper.selectPageDriverCarrier(page, ew);
		if (!CollectionUtils.isEmpty(driverCarrierBOS)) {
			for (DriverCarrierBO driverCarrierBO : driverCarrierBOS) {
				if (Objects.nonNull(driverCarrierBO.getTrailerTypeId())) {
					List<TransportationTypeVO> allServiceType = mdmUtil.getAllFleetTransportType();
					String serviceTypeName = driverCarrierBO.getTrailerTypeId();
					for (TransportationTypeVO transportationTypeVO :
							allServiceType) {
						serviceTypeName = serviceTypeName.replaceAll(transportationTypeVO.getCode(), transportationTypeVO.getValue());
					}
					driverCarrierBO.setTrailerTypeName(serviceTypeName);
				}
				if (Objects.nonNull(driverCarrierBO.getTractorType())) {
					if (TractorTypeEnum.TRACTORVEHICLE.getCode().toString().equals(driverCarrierBO.getTractorType()))
						driverCarrierBO.setTractorTypeName(TractorTypeEnum.TRACTORVEHICLE.getText());
					if (TractorTypeEnum.RECOVERYVEHICLE.getCode().toString().equals(driverCarrierBO.getTractorType()))
						driverCarrierBO.setTractorTypeName(TractorTypeEnum.RECOVERYVEHICLE.getText());
				}
				driverCarrierBO.setCorpName(driverCarrierBO.getLspName());
				if (!Strings.isNullOrEmpty(driverCarrierBO.getCreator())) {
					AccountVO accountVO = uaaUtil.getAccountById(driverCarrierBO.getCreator(), authorization);
					if (Objects.nonNull(accountVO)) {
						driverCarrierBO.setCreator(accountVO.getIdentifier());
					}
				}
			}
		}
		page.setRecords(driverCarrierBOS);
		return page;
	}

	@Override
	public List<CarrierDriverBO> queryUsableCarrier(Long driverId, String carrierPlate) {
		Driver driver = this.selectById(driverId);
		if (Objects.isNull(driver)) throw new BaseException("司机不存在");
		Long lspId = driver.getLspId();
		Long tenantId = driver.getTenantId();
		Wrapper<CarrierDriverBO> ew = new EntityWrapper<>();
		if (Objects.isNull(tenantId)) {
			ew.isNull("tenant_id");//租户为空
		} else {
			ew.eq("tenant_id", tenantId);
		}
		if (Objects.isNull(lspId)) {
			ew.isNull("lsp_id");//承运商为空
		} else {
			ew.eq("lsp_id", lspId);
		}
		ew.like("plate", carrierPlate);
		ew.isNull("driver_id"); //司机为空
		return carrierInfoService.listUsableCarrier(ew);
	}

	@Override
	public boolean bingCarrier(Long driverId, Long carrierId, Long tenantId, String authorization) {
		boolean bindDriverCarrier = driverCarrierBindService.bindDriverCarrier(driverId, carrierId, tenantId);
		bingAndUnbingCarrierToOtm(carrierId, authorization);
		Wrapper<FleetBind> fleetBindEw = new EntityWrapper<>();
		fleetBindEw.eq("resource_id", carrierId)
				.eq("resource_type", TableStatusEnum.STATUS_01.getCode())
				.orderBy("id", false);
		FleetBind fleetBind = fleetBindService.selectOne(fleetBindEw);
		if (Objects.nonNull(fleetBind)) {
			//推送牵引车和挂车到ERP
			carrierInfoService.carrierToERP(authorization, carrierId);
			EntityWrapper<CarrierTrailerBind> trailerBindEW = new EntityWrapper<>();
			trailerBindEW.eq("carrier_id", carrierId)
					.orderBy("id", false);
			CarrierTrailerBind bind = carrierTrailerBindService.selectOne(trailerBindEW);
			if (bind != null) {
				trailerInfoService.authTrailerToERP(bind.getTrailerId(), authorization);
			}
			this.authDriverToERP(authorization,driverId);
		}
		return bindDriverCarrier;
	}

	@Override
	public boolean unbingCarrier(Long driverId, Long carrierId, String authorization) {
		boolean unbindDriverCarrier = driverCarrierBindService.unbindDriverCarrier(driverId, carrierId);
		bingAndUnbingCarrierToOtm(carrierId, authorization);
		WeChatVehicle weChatVehicle = carrierInfoService.selectVehicleByCarrierIdOrTrailerId(carrierId, null);
		carrierInfoService.carrierToERP(authorization, carrierId);
		if (weChatVehicle != null) {
			trailerInfoService.authTrailerToERP(weChatVehicle.getTrailerId(), authorization);
		}
		return unbindDriverCarrier;
	}

	private void bingAndUnbingCarrierToOtm(Long id, String authorization) {
		if (IntegrationEnum.EXPORT.getCode().equals(IntegrationUtil.getIntegrationToOtm())) {
			//获取中联下面的所有管理员账号
			//List<AccountVO> listTenantAccount = uaaUtil.getListTenantAccount(1L, authorization);
			//List<Long> accountIds = new ArrayList<>();
			//for (AccountVO accountVO : listTenantAccount) {
			//    accountIds.add(Long.valueOf(accountVO.getId()));
			//}
			EntityWrapper<FleetBindVO> ew = new EntityWrapper<>();
			ew.eq("resource_id", id)
					.eq("resource_type", TableStatusEnum.STATUS_01.getCode())
					//.in("creator", accountIds)
					.orderBy("id", false);
			List<FleetBindVO> fleetCarrierVOS = fleetBindService.queryBindCarrierList(ew);
			VehicleDTO vehicleDTO = new VehicleDTO();
			WeChatVehicle weChatVehicle = carrierInfoService.selectVehicleByCarrierIdOrTrailerId(id, null);
			if (!CollectionUtils.isEmpty(fleetCarrierVOS)) {
				vehicleDTO.setFleetId(fleetCarrierVOS.get(0).getFleetId());
			} else {
				vehicleDTO.setFleetId(weChatVehicle.getLspId());
			}
			if (!StringUtils.isEmpty(weChatVehicle.getDriverId())) {
				Wrapper<DriverLicense> driverLicenseWrapper = new EntityWrapper<>();
				driverLicenseWrapper.eq("driver_id", weChatVehicle.getDriverId());
				List<DriverLicense> driverLicenses = driverLicenseService.queryIDcard(weChatVehicle.getDriverId());
				if (!CollectionUtils.isEmpty(driverLicenses)) {
					weChatVehicle.setIdCard(driverLicenses.get(0).getLicenseId());
				}
			}
			if (weChatVehicle.getAuthStatus() == 1) {
				if (!StringUtils.isEmpty(weChatVehicle.getTrailerTypeId())) {
					String trailerTypeName = mdmUtil.getTransportTypeByCode(weChatVehicle.getTrailerTypeId()).getValue();
					weChatVehicle.setTrailerTypeName(integrationUtil.getTrailerTypeName(trailerTypeName));
				} else if (weChatVehicle.getTractorType().equals("20") && weChatVehicle.getAuthStatus() == 1) {
					vehicleDTO.setTrailerTypeName("救援车");
					vehicleDTO.setIsActive(IntegrationEnum.ISACTIVE.getCode());
					integrationUtil.exportVehicleToOTM(vehicleDTO);
				} else {
					weChatVehicle.setTrailerTypeName("单车");
					vehicleDTO.setIsActive(IntegrationEnum.NOACTIVE.getCode());
				}
				BeanUtils.copyProperties(weChatVehicle, vehicleDTO);
				integrationUtil.exportVehicleToOTM(vehicleDTO);
			}
		}
	}

	private Wrapper<DriverCarrierBO> buildDriverCarCondition(Map<String, Object> condition) {

		Wrapper<DriverCarrierBO> ew = new EntityWrapper<>();
		if (!Objects.isNull(condition)) {
			//牵引车车牌
			if (condition.containsKey("carrierPlate") && !StringUtils.isEmpty(condition.get("carrierPlate"))) {
				ew.like("lci.plate", condition.get("carrierPlate").toString().trim());
			}

			//承运商名称
			if (condition.containsKey("lspName") && !StringUtils.isEmpty(condition.get("lspName"))) {
				ew.like("c.name", condition.get("lspName").toString().trim());
			}
			//承运商名称
			if (condition.containsKey("tenantId") && !StringUtils.isEmpty(condition.get("tenantId"))) {
				ew.eq("a.tenant_id", condition.get("tenantId").toString().trim());
			}

			//司机姓名
			if (condition.containsKey("name") && !StringUtils.isEmpty(condition.get("name"))) {
				ew.like("a.name", condition.get("name").toString().trim());
			}

			//司机状态
			if (condition.containsKey("status") && !StringUtils.isEmpty(condition.get("status"))) {
				ew.eq("a.status", condition.get("status").toString().trim());
			}

			//司机认证状态
			if (condition.containsKey("authStatus") && !StringUtils.isEmpty(condition.get("authStatus"))) {
				ew.eq("a.auth_status", condition.get("authStatus").toString().trim());
			}

			//牵引车状态
			if (condition.containsKey("carrierStatus") && !StringUtils.isEmpty(condition.get("carrierStatus"))) {
				ew.eq("lci.status", condition.get("carrierStatus").toString().trim());
			}

			//牵引车认证状态
			if (condition.containsKey("carrierAuthStatus") && !StringUtils.isEmpty(condition.get("carrierAuthStatus"))) {
				ew.eq("lci.auth_status", condition.get("carrierAuthStatus").toString().trim());
			}

			if (condition.containsKey("fleetFlag")
					&& !StringUtils.isEmpty(condition.get("fleetFlag"))) {
				// 车队
				if (condition.containsKey("fleetId") && !StringUtils.isEmpty(condition.get("fleetId"))) {
					String fleetId = (String) condition.get("fleetId");
					List<String> fleetIds = Arrays.asList(fleetId.split(","));
					ew.in("b.fleet_id", fleetIds);
				} else {
					throw new BaseException("非车队管理员不能进行改操作");
				}
			}

			if (condition.containsKey("fleetName")
					&& !StringUtils.isEmpty(condition.get("fleetName"))) {
				ew.eq("e.fleet_name", condition.get("fleetName").toString().trim());
			}

			if (condition.containsKey("driverMobile")
					&& !StringUtils.isEmpty(condition.get("driverMobile").toString())) {
				ew.like("a.mobile", condition.get("driverMobile").toString().trim());
			}

		}
		return ew;

	}

	//判断证照有效性
	private Integer getValidStatus(DriverLicense driverLicense, Boolean isHaveAttach) {
		if (Objects.isNull(isHaveAttach)) {
			// 查找证照的附件信息
			Wrapper<DriverLicenseAttach> ew = new EntityWrapper<>();
			ew.eq("license_id", driverLicense.getId()).eq("carrier_id", driverLicense.getDriverId());
			List<DriverLicenseAttach> lspLicenseAttachList = driverLicenseAttachService.selectList(ew);
			if (!CollectionUtils.isEmpty(lspLicenseAttachList)) {
				isHaveAttach = true;
			}
		}

		// 根据时间
		if (Objects.nonNull(driverLicense.getGmtReg()) && Objects.nonNull(driverLicense.getGmtOverdue()) && isHaveAttach &&
				driverLicense.getGmtOverdue().compareTo(driverLicense.getGmtReg()) >= 0 && driverLicense.getGmtOverdue().compareTo(new Date()) >= 0
				&& !StringUtils.isEmpty(driverLicense.getLicenseId())) {
			return LicenseStatusEnum.VALID.getCode();
		} else {
			return LicenseStatusEnum.INVALID.getCode();
		}
	}

	@Override
	public List<String> deleteByIds(Long[] driverIds, String token) {
		try {
			List<String> msgs = new ArrayList<>();
			for (Long id : driverIds) {
				String msg = "";
				Driver driver = this.selectById(id);
				if (Objects.isNull(driver)) {
					msg = "司机:" + driver.getName() + ":未找到对应司机信息";
					msgs.add(msg);
					continue;
				}
				if (AuthStatusEnum.CERTIFICATION.getCode().equals(driver.getAuthStatus())) {
					msg = "司机:" + driver.getName() + ":已认证无法删除";
					msgs.add(msg);
					continue;
				}

				Wrapper<DriverCarrierBind> ewBind = new EntityWrapper<>();
				ewBind.eq("driver_id", id);
				if (driverCarrierBindService.selectCount(ewBind) > 0) {
					msg = "司机:" + driver.getName() + ":已经与牵引车绑定，无法删除";
					msgs.add(msg);
					continue;
				}
				if (Objects.nonNull(driver.getAccountId())) {
					uaaUtil.lockAccount(driver.getAccountId().toString(), token);
				}
				this.deleteById(id);
			}
			return msgs;
		} catch (BaseException e) {
			throw e;
		} catch (Exception e) {
			LOGGER.error("DriverServiceImpl.deleteByIds ERROR:" + e.getMessage());
			throw new BaseException("司机删除异常");
		}
	}

	//-- 来自于原来司机端

	@Override
	@Transactional
	public void updateDriver(DriverBO driverBO) throws BaseException {
		Driver driver = new Driver();
		BeanUtils.copyProperties(driverBO, driver);

		Wrapper<Driver> mobileDriverEntity = new EntityWrapper<>();
		mobileDriverEntity.eq("mobile", driver.getMobile());
		List<Driver> mobileDriverList = baseMapper.selectDriverNoTenant(mobileDriverEntity);
		if (!CollectionUtils.isEmpty(mobileDriverList)) {
			if (!mobileDriverList.get(0).getId().equals(driver.getId()))
				throw new BaseException(DriverExceptionEnum.DRIVER_MOBLIE_EXIST.getCode(), DriverExceptionEnum.DRIVER_MOBLIE_EXIST.getText());
		}
		//计算驾龄
		DateTime fristTime = new DateTime(driverBO.getDriverLicenseFirstDate());
		DateTime nowTime = DateTime.now();
		Period period = new Period(fristTime, nowTime);
		driver.setYod(period.getYears());

		this.updateById(driver);
//        //证件为身份证
//        DriverLicense driverLicense = getDriverLincense(driverBO, LicenseTypeEnum.DRIVER_ID_CARD.getCode(), SubjectTypeEnum.DRIVER.getCode());
//
//        //上传身份证证件照
//        if (!StringUtils.isEmpty(driverBO.getIdCardKey())) {
//            //正面
//            DriverLicenseAttach oldDriverLicenseAttach = driverLicenseAttachService.selectByDriverLicenseId(driverLicense.getId(), driver.getId(), AttachtypeEnum.POSITIVE.getCode());
//
//            if (Objects.isNull(oldDriverLicenseAttach)) {
//                DriverLicenseAttach driverLicenseAttach = `new DriverLicenseAttach();
//                driverLicenseAttach.setDriverId(driverBO.getId());
//                driverLicenseAttach.setAttachKey(driverBO.getIdCardKey());
//                driverLicenseAttach.setDriverLicenseId(driverLicense.getId());
//                driverLicenseAttach.setAttachName(driverBO.getIdCardAttachName());
//                driverLicenseAttach.setAttachType(AttachtypeEnum.POSITIVE.getCode());
////                driverLicenseAttach.setTenantId(driver.getTenantId());
//                driverLicenseAttachService.insert(driverLicenseAttach);
//            } else {
//                if (Objects.isNull(oldDriverLicenseAttach.getAttachKey()) ||
//                        !driverBO.getIdCardKey().equals(oldDriverLicenseAttach.getAttachKey())) {
////                    if(StringUtils.isNotEmpty(oldDriverLicenseAttach.getAttachKey())){
////                        uploadService.deleteFile(oldDriverLicenseAttach.getAttachKey());
////                    }
//                    driverLicenseAttachService.deleteById(oldDriverLicenseAttach.getId());
//                    DriverLicenseAttach driverLicenseAttach = new DriverLicenseAttach();
//                    driverLicenseAttach.setDriverId(driverBO.getId());
//                    driverLicenseAttach.setAttachKey(driverBO.getIdCardKey());
//                    driverLicenseAttach.setDriverLicenseId(driverLicense.getId());
//                    driverLicenseAttach.setAttachName(driverBO.getIdCardAttachName());
//                    driverLicenseAttach.setAttachType(AttachtypeEnum.POSITIVE.getCode());
////                    driverLicenseAttach.setTenantId(driver.getTenantId());
//                    driverLicenseAttachService.insert(driverLicenseAttach);
//                }
//            }
//        }
//
//        //手持身份证
//        if (org.apache.commons.lang3.StringUtils.isNotBlank(driverBO.getWithIdCardKey())) {
//            DriverLicenseAttach oldDriverLicenseAttach = driverLicenseAttachService.selectByDriverLicenseId
//                    (driverLicense.getId(), driver.getId(), AttachtypeEnum.HANDHELD.getCode());
//            if (Objects.isNull(oldDriverLicenseAttach)) {
//                DriverLicenseAttach driverLicenseAttach = new DriverLicenseAttach();
//                driverLicenseAttach.setDriverId(driverBO.getId());
//                driverLicenseAttach.setAttachKey(driverBO.getWithIdCardKey());
//                driverLicenseAttach.setAttachName(driverBO.getWithIdCardAttachName());
//                driverLicenseAttach.setDriverLicenseId(driverLicense.getId());
//                driverLicenseAttach.setAttachType(AttachtypeEnum.HANDHELD.getCode());
////                driverLicenseAttach.setTenantId(driver.getTenantId());
//                driverLicenseAttachService.insert(driverLicenseAttach);
//            } else {
//                if (Objects.isNull(oldDriverLicenseAttach.getAttachKey())
//                        || !driverBO.getWithIdCardKey().equals(oldDriverLicenseAttach.getAttachKey())) {
////                    if(StringUtils.isNotEmpty(oldDriverLicenseAttach.getAttachKey())){
////                        uploadService.deleteFile(oldDriverLicenseAttach.getAttachKey());
////                    }
//                    driverLicenseAttachService.deleteById(oldDriverLicenseAttach.getId());
//                    DriverLicenseAttach driverLicenseAttach = new DriverLicenseAttach();
//                    driverLicenseAttach.setDriverId(driverBO.getId());
//                    driverLicenseAttach.setAttachKey(driverBO.getWithIdCardKey());
//                    driverLicenseAttach.setAttachName(driverBO.getWithIdCardAttachName());
//                    driverLicenseAttach.setDriverLicenseId(driverLicense.getId());
//                    driverLicenseAttach.setAttachType(AttachtypeEnum.HANDHELD.getCode());
////                    driverLicenseAttach.setTenantId(driver.getTenantId());
//                    driverLicenseAttachService.insert(driverLicenseAttach);
//                }
//            }
//        }
//
//        //反面
//        if (org.apache.commons.lang3.StringUtils.isNotBlank(driverBO.getReverseIdCardKey())) {
//            DriverLicenseAttach oldDriverLicenseAttach = driverLicenseAttachService.selectByDriverLicenseId(driverLicense.getId(), driver.getId(), AttachtypeEnum.REVERSE.getCode());
//            if (Objects.isNull(oldDriverLicenseAttach)) {
//                DriverLicenseAttach driverLicenseAttach = new DriverLicenseAttach();
//                driverLicenseAttach.setDriverId(driverBO.getId());
//                driverLicenseAttach.setAttachKey(driverBO.getReverseIdCardKey());
//                driverLicenseAttach.setAttachName(driverBO.getReverseIdCardAttachName());
//                driverLicenseAttach.setDriverLicenseId(driverLicense.getId());
//                driverLicenseAttach.setAttachType(AttachtypeEnum.REVERSE.getCode());
////                driverLicenseAttach.setTenantId(driver.getTenantId());
//                driverLicenseAttachService.insert(driverLicenseAttach);
//            } else {
//                if (Objects.isNull(oldDriverLicenseAttach.getAttachKey()) ||
//                        !driverBO.getReverseIdCardKey().equals(oldDriverLicenseAttach.getAttachKey())) {
////                    if(StringUtils.isNotEmpty(oldDriverLicenseAttach.getAttachKey())){
////                        uploadService.deleteFile(oldDriverLicenseAttach.getAttachKey());
////                    }
//                    driverLicenseAttachService.deleteById(oldDriverLicenseAttach.getId());
//                    DriverLicenseAttach driverLicenseAttach = new DriverLicenseAttach();
//                    driverLicenseAttach.setDriverId(driverBO.getId());
//                    driverLicenseAttach.setAttachKey(driverBO.getReverseIdCardKey());
//                    driverLicenseAttach.setAttachName(driverBO.getReverseIdCardAttachName());
//                    driverLicenseAttach.setDriverLicenseId(driverLicense.getId());
//                    driverLicenseAttach.setAttachType(AttachtypeEnum.REVERSE.getCode());
////                    driverLicenseAttach.setTenantId(driver.getTenantId());
//                    driverLicenseAttachService.insert(driverLicenseAttach);
//                }
//            }
//        }
//
//
//        driverLicense = getDriverLincense(driverBO, LicenseTypeEnum.DRIVER_DRIVER_LICENSE.getCode(), SubjectTypeEnum.DRIVER.getCode());
		getDriverLincense(driverBO, LicenseTypeEnum.DRIVER_DRIVER_LICENSE.getCode(), SubjectTypeEnum.DRIVER.getCode());
//        //上传驾驶证证件照
//        if (org.apache.commons.lang3.StringUtils.isNotBlank(driverBO.getDriverLicenseKey())) {
//            DriverLicenseAttach oldDriverLicenseAttach = driverLicenseAttachService.selectByDriverLicenseId(driverLicense.getId(), driver.getId(), null);
//            if (Objects.isNull(oldDriverLicenseAttach)) {
//                DriverLicenseAttach driverLicenseAttach = new DriverLicenseAttach();
//                driverLicenseAttach.setDriverId(driverBO.getId());
//                driverLicenseAttach.setAttachKey(driverBO.getDriverLicenseKey());
//                driverLicenseAttach.setAttachName(driverBO.getDriverLicenseAttachName());
//                driverLicenseAttach.setDriverLicenseId(driverLicense.getId());
//                driverLicenseAttach.setAttachType(AttachtypeEnum.POSITIVE.getCode());
////                driverLicenseAttach.setTenantId(driver.getTenantId());
//                driverLicenseAttachService.insert(driverLicenseAttach);
//            } else {
//                if (Objects.isNull(oldDriverLicenseAttach.getAttachKey()) ||
//                        !driverBO.getDriverLicenseKey().equals(oldDriverLicenseAttach.getAttachKey())) {
////                    if(StringUtils.isNotEmpty(oldDriverLicenseAttach.getAttachKey())){
////                        uploadService.deleteFile(oldDriverLicenseAttach.getAttachKey());
////                    }
//                    driverLicenseAttachService.deleteById(oldDriverLicenseAttach.getId());
//                    DriverLicenseAttach driverLicenseAttach = new DriverLicenseAttach();
//                    driverLicenseAttach.setDriverId(driverBO.getId());
//                    driverLicenseAttach.setAttachKey(driverBO.getDriverLicenseKey());
//                    driverLicenseAttach.setAttachName(driverBO.getDriverLicenseAttachName());
//                    driverLicenseAttach.setDriverLicenseId(driverLicense.getId());
//                    driverLicenseAttach.setAttachType(AttachtypeEnum.POSITIVE.getCode());
////                    driverLicenseAttach.setTenantId(driver.getTenantId());
//                    driverLicenseAttachService.insert(driverLicenseAttach);
//                }
//            }
//        }
//
//        //运营许可证
//        driverLicense = getDriverLincense(driverBO, LicenseTypeEnum.DRIVER_OPERATING_LICENSE.getCode(), SubjectTypeEnum.DRIVER.getCode());
//        //上传运营许可证证件照
//        if (org.apache.commons.lang3.StringUtils.isNotBlank(driverBO.getOperatingLicenseKey())) {
//            DriverLicenseAttach oldDriverLicenseAttach = driverLicenseAttachService.selectByDriverLicenseId(driverLicense.getId(), driver.getId(), null);
//            if (Objects.isNull(oldDriverLicenseAttach)) {
//                DriverLicenseAttach driverLicenseAttach = new DriverLicenseAttach();
//                driverLicenseAttach.setDriverId(driverBO.getId());
//                driverLicenseAttach.setAttachKey(driverBO.getOperatingLicenseKey());
//                driverLicenseAttach.setAttachName(driverBO.getOperatingLicenseAttachName());
//                driverLicenseAttach.setDriverLicenseId(driverLicense.getId());
//                driverLicenseAttach.setAttachType(AttachtypeEnum.POSITIVE.getCode());
////                driverLicenseAttach.setTenantId(driver.getTenantId());
//                driverLicenseAttachService.insert(driverLicenseAttach);
//            } else {
//                if (Objects.isNull(oldDriverLicenseAttach.getAttachKey()) ||
//                        !driverBO.getOperatingLicenseKey().equals(oldDriverLicenseAttach.getAttachKey())) {
////                    if(StringUtils.isNotEmpty(oldDriverLicenseAttach.getAttachKey())){
////                        uploadService.deleteFile(oldDriverLicenseAttach.getAttachKey());
////                    }
//                    driverLicenseAttachService.deleteById(oldDriverLicenseAttach.getId());
//                    DriverLicenseAttach driverLicenseAttach = new DriverLicenseAttach();
//                    driverLicenseAttach.setDriverId(driverBO.getId());
//                    driverLicenseAttach.setAttachKey(driverBO.getOperatingLicenseKey());
//                    driverLicenseAttach.setAttachName(driverBO.getOperatingLicenseAttachName());
//                    driverLicenseAttach.setDriverLicenseId(driverLicense.getId());
//                    driverLicenseAttach.setAttachType(AttachtypeEnum.POSITIVE.getCode());
////                    driverLicenseAttach.setTenantId(driver.getTenantId());
//                    driverLicenseAttachService.insert(driverLicenseAttach);
//                }
//            }
//        }
	}

	@Override
	public void updateDriverAttach(AttachVO driverAttachVO, String authorization) throws BaseException {
		if (Strings.isNullOrEmpty(driverAttachVO.getKeyTypeName())) throw new BaseException("请匹配证件类型");
		int idCardIndex = driverAttachVO.getKeyTypeName().toLowerCase().indexOf("idcard");
		Long licenseTypeId = null;
		String attachType = null;

		if (idCardIndex >= 0) {
			LicenseTypeVo licenseTypeVO = mdmUtil.getLicenseTypeByCode(LicenseTypeEnum.DRIVER_ID_CARD.getCode(), SubjectTypeEnum.DRIVER.getCode());
			if (driverAttachVO.getKeyTypeName().equals("idCard")) {
				licenseTypeId = licenseTypeVO.getId();
				attachType = AttachtypeEnum.POSITIVE.getCode();
			} else if (driverAttachVO.getKeyTypeName().equals("withIdCard")) {
				licenseTypeId = licenseTypeVO.getId();
				attachType = AttachtypeEnum.HANDHELD.getCode();
			} else if (driverAttachVO.getKeyTypeName().equals("reverseIdCard")) {
				licenseTypeId = licenseTypeVO.getId();
				attachType = AttachtypeEnum.REVERSE.getCode();
			} else {
				throw new BaseException("未找到匹配类型");
			}
		} else {
			LicenseTypeVo licenseTypeVO;
			if (driverAttachVO.getKeyTypeName().equals("driverLicense")) {
				licenseTypeVO = mdmUtil.getLicenseTypeByCode(LicenseTypeEnum.DRIVER_DRIVER_LICENSE.getCode(), SubjectTypeEnum.DRIVER.getCode());
			} else if (driverAttachVO.getKeyTypeName().equals("operatingLicense")) {
				licenseTypeVO = mdmUtil.getLicenseTypeByCode(LicenseTypeEnum.DRIVER_OPERATING_LICENSE.getCode(), SubjectTypeEnum.DRIVER.getCode());
			} else {
				throw new BaseException("未找到匹配类型");
			}
			licenseTypeId = licenseTypeVO.getId();
			attachType = AttachtypeEnum.POSITIVE.getCode();
		}
		ModifyDriverBO modifyDriverBO = new ModifyDriverBO();
		modifyDriverBO.setId(driverAttachVO.getDriverId());
		List<ModifyDriverLicenseBO> modifyDriverLicenseBOS = new ArrayList<>();
		ModifyDriverLicenseBO modifyDriverLicenseBO = new ModifyDriverLicenseBO();
		modifyDriverLicenseBO.setLicenseTypeId(licenseTypeId);
		//附件信息
		List<DriverLicenseAttach> driverLicenseAttaches = new ArrayList<>();
		DriverLicenseAttach driverLicenseAttach = new DriverLicenseAttach();

		driverLicenseAttach.setAttachKey(driverAttachVO.getKey());
		driverLicenseAttach.setAttachName(driverAttachVO.getAttachName());
		driverLicenseAttach.setAttachType(attachType);

		driverLicenseAttaches.add(driverLicenseAttach);
		modifyDriverLicenseBO.setDriverLicenseAttachList(driverLicenseAttaches);
		modifyDriverLicenseBOS.add(modifyDriverLicenseBO);
		modifyDriverBO.setModifyDriverLicenseBOList(modifyDriverLicenseBOS);
//        是否有新增或更改操作
		if (this.updateLicense(modifyDriverBO)) {
			//自动识别
			//修改身份证信息需要进行验证
			if (idCardIndex >= 0) {
				DriverLicense driverLicense = getLicenseByIdOrType(modifyDriverLicenseBO, modifyDriverBO.getId());
				if (Objects.nonNull(driverLicense))
					driverLicenseService.updateLicense(driverLicenseAttach.getAttachKey(), driverLicense.getId(), driverLicenseAttach.getAttachType(), authorization);
			}
		}
//        if (idCardIndex >= 0){
//            IdentityCardInfoVO identityCardInfoVO=null;
//            if(driverLicenseAttach.getAttachType().equals("01"))
//                identityCardInfoVO=devopUtil.getIdentityCardInfo(driverLicenseAttach.getAttachKey(),"1",authorization);
//            else if(driverLicenseAttach.getAttachType().equals("02")){
//                identityCardInfoVO=devopUtil.getIdentityCardInfo(driverLicenseAttach.getAttachKey(),"2",authorization);
//            }
//            if(Objects.nonNull(identityCardInfoVO)){
//                DriverLicense license = getLicenseByIdOrType(modifyDriverLicenseBO,driverAttachVO.getId());
//                if(driverLicenseAttach.getAttachType().equals("01")){
//                    if(!Strings.isNullOrEmpty(identityCardInfoVO.getNumber()))license.setLicenseId(identityCardInfoVO.getNumber());
//                }
//                else if(driverLicenseAttach.getAttachType().equals("02")){
//                    if(!Strings.isNullOrEmpty(identityCardInfoVO.getStart_date()))license.setGmtReg(new Date(identityCardInfoVO.getStart_date()));
//                    if(!Strings.isNullOrEmpty(identityCardInfoVO.getEnd_date()))license.setGmtOverdue(new Date(identityCardInfoVO.getStart_date()));
//                }
//                driverLicenseService.updateById(license);
//            }
//        }
	}

	@Override
	public DriverBO getDriverById(Long id) throws BaseException {
//        Account account = uaaUtil.getLoginAccount();
		Driver driver = this.selectById(id);
		if (Objects.isNull(driver)) {
			throw new BaseException(DriverExceptionEnum.DRIVER_INFO_NOT_EXIST.getCode(), DriverExceptionEnum.DRIVER_INFO_NOT_EXIST.getText());
		}

		DriverBO driverBO = new DriverBO();
		BeanUtils.copyProperties(driver, driverBO);
		Long lspId = driver.getLspId();
		LspInfo lspInfo = lspInfoService.selectById(lspId);
		if (Objects.nonNull(lspInfo)) {
			driverBO.setLspName(lspInfo.getName());
		}

		//身份证
		List<String> attachTypes = Lists.newArrayList();
		attachTypes.add(AttachtypeEnum.POSITIVE.getCode());
		attachTypes.add(AttachtypeEnum.HANDHELD.getCode());
		attachTypes.add(AttachtypeEnum.REVERSE.getCode());
		getDriverBO(driverBO, LicenseTypeEnum.DRIVER_ID_CARD.getCode(), SubjectTypeEnum.DRIVER.getCode(), attachTypes);

		//驾驶证
		List<String> attachTypes1 = Lists.newArrayList();
		attachTypes1.add(AttachtypeEnum.POSITIVE.getCode());
		getDriverBO(driverBO, LicenseTypeEnum.DRIVER_DRIVER_LICENSE.getCode(), SubjectTypeEnum.DRIVER.getCode(), attachTypes);

		//运营许可证
		getDriverBO(driverBO, LicenseTypeEnum.DRIVER_OPERATING_LICENSE.getCode(), SubjectTypeEnum.DRIVER.getCode(), null);

		return driverBO;
	}


	@Override
	public DriverCertificationBO getDriverCertification(Long drivertId) throws BaseException {
		//创建司机信息完善的 bo
		DriverCertificationBO driverCertificationBO = new DriverCertificationBO();
		driverCertificationBO.setDriverInfoStatus(true);
		driverCertificationBO.setVehicleInfoStatus(true);

		Boolean blnDriverInfoStatus = true;
		Boolean blnVechieInfoStatus = true;

		TrailerInfoBO trailerInfoBO = null;

		//是否可以报班
		Boolean blnIsCanCheckin = false;
		//不能报班的原因
		List<String> listReason = Lists.newArrayList();


		Driver driver = this.selectById(drivertId);
		if (Objects.isNull(driver)) {
			throw new BaseException(DriverExceptionEnum.DRIVER_INFO_NOT_EXIST.getCode(), DriverExceptionEnum.DRIVER_INFO_NOT_EXIST.getText());
		}

		//判断司机姓名 手机号 性别 是否完善
		if (StringUtils.isEmpty(driver.getName()) || Objects.isNull(driver.getSex()) || StringUtils.isEmpty(driver
				.getMobile())) {
			blnDriverInfoStatus = false;
		}

		//判断身份证信息
		if (blnDriverInfoStatus) {
			List<String> attachTypes = Lists.newArrayList();
			attachTypes.add(AttachtypeEnum.POSITIVE.getCode());
			attachTypes.add(AttachtypeEnum.HANDHELD.getCode());
			attachTypes.add(AttachtypeEnum.REVERSE.getCode());
			//判断身份证信息
			blnDriverInfoStatus = getDriverStatus(driver.getId(), LicenseTypeEnum.DRIVER_ID_CARD.getCode(), SubjectTypeEnum.DRIVER.getCode(), attachTypes);
		}

		//判断驾驶证
		if (blnDriverInfoStatus) {
			blnDriverInfoStatus = getDriverStatus(driver.getId(), LicenseTypeEnum.DRIVER_DRIVER_LICENSE.getCode(), SubjectTypeEnum.DRIVER.getCode(), null);
		}

		//判断从业许可证
		if (blnDriverInfoStatus) {
			blnDriverInfoStatus = getDriverStatus(driver.getId(), LicenseTypeEnum.DRIVER_OPERATING_LICENSE.getCode(), SubjectTypeEnum.DRIVER.getCode(), null);
		}

		//判断车辆信息
		CarrierInfoBO carrierInfoBO = carrierInfoService.selectByDriverId(drivertId);


		if (Objects.nonNull(carrierInfoBO)) {
			//获取挂车信息
			trailerInfoBO = trailerInfoService.selectByCarrierInfoId(carrierInfoBO.getId());

			//判断牵引车车牌
			if (StringUtils.isEmpty(carrierInfoBO.getPlate())) {
				blnVechieInfoStatus = false;
			}
			//判断牵引车 行驶证信息
			if (blnVechieInfoStatus) {
				blnVechieInfoStatus = carrierInfoService.getCarrierStatus(carrierInfoBO.getId(), LicenseTypeEnum.VEHICLE_VEHICLE_LICENSE.getCode(), SubjectTypeEnum.VEHICLE.getCode());
			}

			//判断牵引车 运营许可证信息
			if (blnVechieInfoStatus) {
				blnVechieInfoStatus = carrierInfoService.getCarrierStatus(carrierInfoBO.getId(), LicenseTypeEnum.VEHICLE_OPERATING_LICENSE.getCode(), SubjectTypeEnum.VEHICLE.getCode());
			}

			if (blnVechieInfoStatus) {
				if (Objects.nonNull(trailerInfoBO)) {
					//判断挂车车牌
					if (StringUtils.isEmpty(trailerInfoBO.getPlate())) {
						blnVechieInfoStatus = false;
					}

					if (blnVechieInfoStatus) {
						blnVechieInfoStatus = trailerInfoService.getTrailerStatus(trailerInfoBO.getId(), LicenseTypeEnum.VEHICLE_VEHICLE_LICENSE.getCode(), SubjectTypeEnum.VEHICLE.getCode());
					}

					if (blnVechieInfoStatus) {
						blnVechieInfoStatus = trailerInfoService.getTrailerStatus(trailerInfoBO.getId(), LicenseTypeEnum.VEHICLE_OPERATING_LICENSE.getCode(), SubjectTypeEnum.VEHICLE.getCode());
					}
				} else {
					blnVechieInfoStatus = false;
				}
			}
		} else {
			blnVechieInfoStatus = false;
		}
		driverCertificationBO.setDriverInfoStatus(blnDriverInfoStatus);
		driverCertificationBO.setVehicleInfoStatus(blnVechieInfoStatus);

		//判断司机是否认证
		if (driver.getAuthStatus().equals(AuthStatusEnum.UNAUTHORIZED.getCode())) {
			listReason.add("司机未认证");
		}

		//判断司机是否启用
		if (driver.getStatus().equals(StatusEnum.DISCONTINUAT.getCode())) {
			listReason.add("司机未启用");
		}

		//判断司机是否绑定牵引车，如果没有绑定，也不能报班
		if (Objects.nonNull(carrierInfoBO)) {
			//判断绑定的牵引车是否认证，没有认证，不能报班
			if (carrierInfoBO.getAuthStatus().equals(AuthStatusEnum.UNAUTHORIZED.getCode())) {
				listReason.add("牵引车未认证");
			}
			if (carrierInfoBO.getStatus().equals(StatusEnum.DISCONTINUAT.getCode())) {
				listReason.add("牵引车未启用");
			}
		} else {
			listReason.add("未绑定牵引车");
		}

		//判断绑定的牵引车是否绑定挂车，如果没有绑定，也不能报班
		if (Objects.nonNull(trailerInfoBO)) {
			// 判断绑定的挂车是否认证，没有认证，不能报班
			if (trailerInfoBO.getAuthStatus().equals(AuthStatusEnum.UNAUTHORIZED.getCode())) {
				listReason.add("挂车未认证");
			}
			if (trailerInfoBO.getStatus().equals(StatusEnum.DISCONTINUAT.getCode())) {
				listReason.add("挂车未启用");
			}
		} else {
			listReason.add("未绑定挂车");
		}

		//加入不能报班的原因
		if (CollectionUtils.isEmpty(listReason)) {
			blnIsCanCheckin = true;
		}

		driverCertificationBO.setCanCheckin(blnIsCanCheckin);
		driverCertificationBO.setNoCheckinReason(listReason);

		return driverCertificationBO;
	}


	/**
	 * 导出司机/车辆信息到excel
	 */
	@Override
	public List<DriverExportDTO> exportDriver(Map<String, String> condition) {
		EntityWrapper<DriverExportDTO> ew = new EntityWrapper<>();
		return baseMapper.selectExportDriverNoTenant(ew, condition);
	}

	/**
	 * 得到证照信息
	 */
	private DriverLicense getDriverLincense(DriverBO driverBO, String typeCode, String subjectCode) {
		LicenseTypeVo licenseTypeBO = mdmUtil.getLicenseTypeByCode(typeCode, subjectCode);
		if (Objects.isNull(licenseTypeBO)) {
			throw new BaseException("缺少证照类型");
		}

		EntityWrapper<DriverLicense> ewdl = new EntityWrapper<>();
		ewdl.eq("license_type_id", licenseTypeBO.getId());
		ewdl.eq("driver_id", driverBO.getId());
		List<DriverLicense> dls = driverLicenseService.selectList(ewdl);
		DriverLicense driverLicense = new DriverLicense();

		//如果不存在
		if (CollectionUtils.isEmpty(dls)) {
			if (typeCode.equals(LicenseTypeEnum.DRIVER_ID_CARD.getCode())) {
				driverLicense.setLicenseId(driverBO.getLicenseId());
			}

			if (typeCode.equals(LicenseTypeEnum.DRIVER_DRIVER_LICENSE.getCode())) {
				driverLicense.setLicenseId(driverBO.getDriverLicenseId());
				driverLicense.setGmtReg(driverBO.getDriverLicenseStartDate());
				driverLicense.setGmtOverdue(driverBO.getDriverLicenseEndDate());
				driverLicense.setGmtFirst(driverBO.getDriverLicenseFirstDate());
			}

			driverLicense.setLicenseTypeId(licenseTypeBO.getId());
			driverLicense.setDriverId(driverBO.getId());
			driverLicenseService.insert(driverLicense);
		} else {
			//存在
			driverLicense = dls.get(0);
			//如果是身份证
			if (typeCode.equals(LicenseTypeEnum.DRIVER_ID_CARD.getCode())) {
				if (!StringUtils.isEmpty(driverBO.getLicenseId())) {
					driverLicense.setLicenseId(driverBO.getLicenseId());
					driverLicenseService.updateById(driverLicense);
				}
			}

			//如果是驾照
			if (typeCode.equals(LicenseTypeEnum.DRIVER_DRIVER_LICENSE.getCode())) {
				if (!StringUtils.isEmpty(driverBO.getDriverLicenseId())) {
					driverLicense.setLicenseId(driverBO.getDriverLicenseId());
					driverLicense.setGmtFirst(driverBO.getDriverLicenseFirstDate());
					driverLicense.setGmtReg(driverBO.getDriverLicenseStartDate());
					driverLicense.setGmtOverdue(driverBO.getDriverLicenseEndDate());
					driverLicenseService.updateById(driverLicense);
				}
			}
		}
		return driverLicense;
	}

	/**
	 * 获取司机的BO
	 */
	private DriverBO getDriverBO(DriverBO driverBO, String typeCode, String
			subjectCode, List<String> attachTypes) {
		Long driverId = driverBO.getId();
		String width = "160";
		String heigth = "105";

		LicenseTypeVo licenseTypeBO = mdmUtil.getLicenseTypeByCode(typeCode, subjectCode);
		if (Objects.isNull(licenseTypeBO)) {
			throw new BaseException("缺少证照类型");
		}
		EntityWrapper<DriverLicense> ewdl = new EntityWrapper<>();
		ewdl.eq("license_type_id", licenseTypeBO.getId());
		ewdl.eq("driver_id", driverId);
		List<DriverLicense> dls = driverLicenseService.selectList(ewdl);
		if (!org.apache.commons.collections4.CollectionUtils.isEmpty(dls)) {
			DriverLicense driverLicense = dls.get(0);
			DriverLicenseBO driverLicenseBO = new DriverLicenseBO();
			BeanUtils.copyProperties(driverLicense, driverLicenseBO);
			if (typeCode.equals(LicenseTypeEnum.DRIVER_ID_CARD.getCode())) {
				//设置身份证
				driverBO.setLicenseId(driverLicenseBO.getLicenseId());
				if (!Objects.isNull(driverLicenseBO.getId())) {
					//附件类型
					if (attachTypes.contains(AttachtypeEnum.POSITIVE.getCode())) {
						DriverLicenseAttach driverLicenseAttach = driverLicenseAttachService.selectByDriverLicenseId(driverLicenseBO.getId(), driverId, AttachtypeEnum.POSITIVE.getCode());
						if (Objects.nonNull(driverLicenseAttach)) {
							driverBO.setIdCardKey(driverLicenseAttach.getAttachKey());
							driverBO.setIdCardAttachName(driverLicenseAttach.getAttachName());
							driverBO.setIdCardPath(uploadService.getStrUrl(driverLicenseAttach.getAttachKey(), width, heigth));
						}
					}

					if (attachTypes.contains(AttachtypeEnum.HANDHELD.getCode())) {
						DriverLicenseAttach driverLicenseAttach = driverLicenseAttachService.selectByDriverLicenseId(driverLicenseBO.getId(), driverId, AttachtypeEnum.HANDHELD.getCode());
						if (Objects.nonNull(driverLicenseAttach)) {
							driverBO.setWithIdCardKey(driverLicenseAttach.getAttachKey());
							driverBO.setWithIdCardAttachName(driverLicenseAttach.getAttachName());
							driverBO.setWithIdCardPath(uploadService.getStrUrl(driverLicenseAttach.getAttachKey(), width, heigth));
						}
					}

					if (attachTypes.contains(AttachtypeEnum.REVERSE.getCode())) {
						DriverLicenseAttach driverLicenseAttach = driverLicenseAttachService.selectByDriverLicenseId(driverLicenseBO.getId(), driverId, AttachtypeEnum.REVERSE.getCode());
						if (Objects.nonNull(driverLicenseAttach)) {
							driverBO.setReverseIdCardKey(driverLicenseAttach.getAttachKey());
							driverBO.setReverseIdCardAttachName(driverLicenseAttach.getAttachName());
							driverBO.setReverseIdCardPath(uploadService.getStrUrl(driverLicenseAttach.getAttachKey(), width, heigth));
						}
					}
				}

			}

			//驾照
			if (typeCode.equals(LicenseTypeEnum.DRIVER_DRIVER_LICENSE.getCode())) {
				//设置驾驶证
				driverBO.setDriverLicenseId(driverLicenseBO.getLicenseId());
				driverBO.setDriverLicenseStartDate(driverLicenseBO.getGmtReg());
				driverBO.setDriverLicenseEndDate(driverLicenseBO.getGmtOverdue());
				driverBO.setDriverLicenseFirstDate(driverLicenseBO.getGmtFirst());
				DriverLicenseAttach driverLicenseAttach = driverLicenseAttachService.selectByDriverLicenseId(driverLicenseBO.getId(), driverId, AttachtypeEnum.POSITIVE.getCode());
				if (Objects.nonNull(driverLicenseAttach)) {
					driverBO.setDriverLicenseKey(driverLicenseAttach.getAttachKey());
					driverBO.setDriverLicenseAttachName(driverLicenseAttach.getAttachName());
					driverBO.setDriverLicensePath(uploadService.getStrUrl(driverLicenseAttach.getAttachKey(), width, heigth));
				}
			}

			//从业许可证
			if (typeCode.equals(LicenseTypeEnum.DRIVER_OPERATING_LICENSE.getCode())) {
				DriverLicenseAttach driverLicenseAttach = driverLicenseAttachService.selectByDriverLicenseId(driverLicenseBO.getId(), driverId, AttachtypeEnum.POSITIVE.getCode());
				if (Objects.nonNull(driverLicenseAttach)) {
					driverBO.setOperatingLicenseKey(driverLicenseAttach.getAttachKey());
					driverBO.setOperatingLicenseAttachName(driverLicenseAttach.getAttachName());
					driverBO.setOperatingLicensePath(uploadService.getStrUrl(driverLicenseAttach.getAttachKey(), width, heigth));
				}
			}
		}
		return driverBO;
	}

	/**
	 * 司机信息的完善状态
	 */
	private Boolean getDriverStatus(Long drivertId, String typeCode, String
			subjectCode, List<String> attachTypes) {
		Boolean blnDriverStatus = true;

		//判断证照信息
		LicenseTypeVo licenseTypeBO = mdmUtil.getLicenseTypeByCode(typeCode, subjectCode);
		if (Objects.isNull(licenseTypeBO)) {
			throw new BaseException("缺少证照类型");
		}
		EntityWrapper<DriverLicense> ewdl = new EntityWrapper<>();
		ewdl.eq("license_type_id", licenseTypeBO.getId()).eq("driver_id", drivertId);
		List<DriverLicense> dls = driverLicenseService.selectList(ewdl);
		if (!org.apache.commons.collections4.CollectionUtils.isEmpty(dls)) {
			DriverLicense driverLicense = dls.get(0);
			DriverLicenseBO driverLicenseBO = new DriverLicenseBO();
			//身份证
			if (typeCode.equals(LicenseTypeEnum.DRIVER_ID_CARD.getCode())) {
				//身份证号为空
				if (org.apache.commons.lang3.StringUtils.isBlank(driverLicense.getLicenseId())) {
					return false;
				}
			}
			//驾照
			if (typeCode.equals(LicenseTypeEnum.DRIVER_DRIVER_LICENSE.getCode())) {
				if (org.apache.commons.lang3.StringUtils.isBlank(driverLicense.getLicenseId())) {
					return false;
				}
			}

			BeanUtils.copyProperties(driverLicense, driverLicenseBO);
			if (Objects.nonNull(driverLicenseBO.getId())) {
				if (!org.apache.commons.collections4.CollectionUtils.isEmpty(attachTypes)) {
					for (String attachType : attachTypes) {
						DriverLicenseAttach driverLicenseAttach = driverLicenseAttachService.selectByDriverLicenseId(driverLicenseBO.getId(), drivertId, attachType);
						if (Objects.isNull(driverLicenseAttach)) {
							blnDriverStatus = false;
							break;
						}
					}
				} else {
					DriverLicenseAttach driverLicenseAttach = driverLicenseAttachService.selectByDriverLicenseId(driverLicenseBO.getId(), drivertId, AttachtypeEnum.POSITIVE.getCode());
					if (Objects.isNull(driverLicenseAttach)) {
						blnDriverStatus = false;
					}
				}
			}
		} else {
			blnDriverStatus = false;
		}

		return blnDriverStatus;
	}

	@Override
	public DriverBO loginDriver(String moblie) throws BaseException {

		EntityWrapper<Driver> entityWrapper = new EntityWrapper<>();
		entityWrapper.eq("mobile", moblie);

		List<Driver> driverList = this.selectList(entityWrapper);
		if (CollectionUtils.isEmpty(driverList)) {
			throw new BaseException(DriverExceptionEnum.DRIVER_INFO_NOT_EXIST.getCode(), DriverExceptionEnum.DRIVER_INFO_NOT_EXIST.getText());
		}
		DriverBO driverBO = new DriverBO();
		BeanUtils.copyProperties(driverList.get(0), driverBO);
		return driverBO;
	}

	@Override
	public Driver registDriver(String mobile, Long accountId, Long tenantId) throws BaseException {
		if (StringUtils.isEmpty(mobile)) {
			throw new BaseException(DriverExceptionEnum.DRIVER_MOBLIE_IS_NULL.getCode(), DriverExceptionEnum.DRIVER_MOBLIE_IS_NULL.getText());
		}

		if (!RegexUtil.check(RegexUtil.REGEX_MOBILE, mobile)) {
			throw new BaseException(DriverExceptionEnum.MOBILE_FORMAT_ERROR.getCode(), DriverExceptionEnum.MOBILE_FORMAT_ERROR.getText());
		}

		//判断司机是否注册过
		EntityWrapper<Driver> entityWrapper = new EntityWrapper<>();
		entityWrapper.eq("mobile", mobile);
		List<Driver> list = this.selectList(entityWrapper);
		if (!list.isEmpty()) {
			throw new BaseException(DriverExceptionEnum.DRIVER_MOBLIE_EXIST.getCode(), DriverExceptionEnum.DRIVER_MOBLIE_EXIST.getText());
		}
		//新增司机数据
		Driver driver = new Driver();
		driver.setMobile(mobile);
		driver.setAccountId(accountId);
		//默认服务类型为板车运输
		driver.setServiceType("fleet");
		driver.setStatus(StatusEnum.DISCONTINUAT.getCode());
		driver.setAuthStatus(AuthStatusEnum.UNAUTHORIZED.getCode());
		driver.setTenantId(tenantId);
		driver.setCreateFrom(SourceEnum.WEIXIN.getText());
		Wrapper<LspInfo> ew = new EntityWrapper<>();
		ew.eq("tenant_id", tenantId);
		LspInfo lspInfo = lspInfoService.selectOne(ew);
		if (Objects.nonNull(lspInfo)) {
			driver.setLspId(lspInfo.getId());
		}
		this.insert(driver);
		return driver;
	}


	@Override
	public List<DriverBO> getAllDriver() throws BaseException {
		List<Driver> list = this.selectList(null);
		List<DriverBO> listBO = new ArrayList<>();
		for (Driver driver : list) {
			DriverBO driverBO = new DriverBO();
			BeanUtils.copyProperties(driver, driverBO);
			listBO.add(driverBO);
		}
		return listBO;
	}

	@Override
	@JmsListener(destination = "${mqName.updateDriver}", containerFactory = "jmsListenerContainerQueue")
	public void updateDriverAccountId(String accountDriverVO) throws BaseException {
		JSONObject json = JSONObject.parseObject(accountDriverVO);
		AccountDriverVO accountDriverInfo = json.toJavaObject(AccountDriverVO.class);
		Driver driver = new Driver();
		driver.setId(accountDriverInfo.getDriverId());
		driver.setAccountId(accountDriverInfo.getAccountId());
		this.updateById(driver);
		Driver driverInfo = this.selectById(accountDriverInfo.getDriverId());
		Wrapper<User> wrapper = new EntityWrapper<>();
		wrapper.eq("mobile", driverInfo.getMobile());
		User user = new User();
		String accountId = accountDriverInfo.getAccountId().toString();
		user.setAccountId(accountId);
		iUserService.update(user, wrapper);
	}

	/**
	 * 向mq发送消息
	 */
	@Override
	public void driverSendMessage(Driver driver, String authorization) {
		Destination destination = new ActiveMQQueue(mqNameRegistDriver);
		if (driver == null) {
			throw new BaseException("未查询到司机信息");
		}
		RegistDriverVO registDriverVO = new RegistDriverVO();
		registDriverVO.setDriverName(driver.getName());
		registDriverVO.setMobile(driver.getMobile());
		registDriverVO.setDriverId(driver.getId());
		registDriverVO.setTenantId(driver.getTenantId());
		JwtAccountVO jwtAccountVO = AccountUtil.getAccountInfoFromSecurityContext();
		if (jwtAccountVO != null) {
			registDriverVO.setCreator(jwtAccountVO.getAccountId());
		}
		List<NameValuePair> headNamePairs = Lists.newArrayList();
		headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
		List<NameValuePair> pramsNamePairs = Lists.newArrayList();
		pramsNamePairs.add(new BasicNameValuePair("identifier", driver.getMobile()));
		String isOpen = HttpClientUtil.get(accountGetAccountuRrl, headNamePairs, pramsNamePairs, socketTimeout);
		JSONObject jsonObject = JSONObject.parseObject(isOpen);
		if (Integer.valueOf(jsonObject.get("code").toString()) == 0) {
			throw new BaseException("该手机号已被注册！");
		}
		String tenantInfo = JSON.toJSONString(registDriverVO);
		jmsTemplate.convertAndSend(destination, tenantInfo);

	}

	/**
	 * 接受uaa注册账号的信息来添加司机信息
	 */
	@Override
	@JmsListener(destination = "${mqName.account}", containerFactory = "jmsListenerContainerQueue")
	public void getDriverIfon(String registDriverInfo) throws BaseException {
		LOGGER.info("getDriverIfon（uaa传过来的数据） params : {} ", registDriverInfo);
		JSONObject json = JSONObject.parseObject(registDriverInfo);
		RegistDriverVO registDriverVO = json.toJavaObject(RegistDriverVO.class);
		registDriver(registDriverVO);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void registDriver(RegistDriverVO registDriverVO) {
		LOGGER.info("registDriver（微信公众号注册司机数据） params : {} ", registDriverVO);
		if (StringUtils.isEmpty(registDriverVO.getMobile())) {
			throw new BaseException(DriverExceptionEnum.DRIVER_MOBLIE_IS_NULL.getCode(), DriverExceptionEnum.DRIVER_MOBLIE_IS_NULL.getText());
		}
		if (!RegexUtil.check(RegexUtil.REGEX_MOBILE, registDriverVO.getMobile())) {
			throw new BaseException(DriverExceptionEnum.MOBILE_FORMAT_ERROR.getCode(), DriverExceptionEnum.MOBILE_FORMAT_ERROR.getText());
		}
		//判断司机是否注册过
		EntityWrapper<Driver> entityWrapper = new EntityWrapper<>();
		entityWrapper.eq("mobile", registDriverVO.getMobile());
		List<Driver> driverList = baseMapper.selectDriverNoTenant(entityWrapper);
		if (!driverList.isEmpty()) {
			throw new BaseException(DriverExceptionEnum.DRIVER_MOBLIE_EXIST.getCode(), DriverExceptionEnum.DRIVER_MOBLIE_EXIST.getText());
		}
		//插入创建失败司机数据
		DriverCreateLog driverCreateLog = new DriverCreateLog();
		driverCreateLog.setMobile(registDriverVO.getMobile());
		driverCreateLog.setAccountId(registDriverVO.getId().toString());
		driverCreateLog.setTenantId(registDriverVO.getTenantId());
		driverCreateLog.setGmtCreate(new Date());
		driverCreateLog.setGmtModify(new Date());
		driverCreateLog.setIsSuccess(0);
		driverCreateLog.setTryTimes(0);
		driverCreateLog.setCreator(registDriverVO.getCreator());
		try {
			insertDriverInfo(registDriverVO);
		} catch (BaseException e) {
			LOGGER.error(e.getMessage());
		} catch (Exception e) {
			iDriverCreateLogService.insert(driverCreateLog);
			//新启线程重试三次--应该会有连接关闭风险
			new Thread(() -> {
				for (int i = 0; i < 3; i++) {
					boolean driver = insertDriverInfo(registDriverVO);
					if (driver) {
						driverCreateLog.setGmtModify(new Date());
						driverCreateLog.setIsSuccess(1);
						iDriverCreateLogService.updateById(driverCreateLog);
						i = 3;
					} else {
						driverCreateLog.setTryTimes(i++);
						driverCreateLog.setGmtModify(new Date());
						iDriverCreateLogService.updateById(driverCreateLog);
					}
				}
			}).start();
		}
	}

	private boolean insertDriverInfo(RegistDriverVO registDriverVO) {
		//新增司机数据
		Driver driver = new Driver();
		driver.setName(registDriverVO.getDriverName());
		driver.setMobile(registDriverVO.getMobile());
		driver.setAccountId(registDriverVO.getId());
		//默认服务类型为板车运输
		driver.setServiceType("fleet");
		driver.setStatus(StatusEnum.DISCONTINUAT.getCode());
		driver.setAuthStatus(AuthStatusEnum.UNAUTHORIZED.getCode());
		driver.setTenantId(registDriverVO.getTenantId());
		driver.setCreateFrom(SourceEnum.WEIXIN.getText());
		driver.setCreator(registDriverVO.getCreator());
		Wrapper<LspInfo> ew = new EntityWrapper<>();
		ew.eq("tenant_id", registDriverVO.getTenantId())
				.orderBy("id", false);
		List<LspInfo> lspInfos = lspInfoService.selectListNoTenant(ew);
		if (!CollectionUtils.isEmpty(lspInfos)) {
			driver.setLspId(lspInfos.get(0).getId());
		}
		LOGGER.info("insertDriverInfo（Driver数据） params : {} ", driver);
		this.insert(driver);
		User user = new User();
		user.setName(driver.getName());
		user.setMobile(driver.getMobile());
		user.setDepartment("driver");
		user.setLspId(driver.getLspId());
		user.setCreateUser(registDriverVO.getCreator());
		user.setModifiedUser(registDriverVO.getCreator());
		LOGGER.info("insertDriverInfo（addUser权限用户数据） params : {} ", user);
		iUserService.addUser(user);
		return true;
	}

	/**
	 * 更新司机基本信息
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Driver updateDriver(DriverBasicVO driver, String authorization) {
		try {
			if (driver.getBusinessSite() != null
					&& driver.getBusinessSite().length() > 500) {
				throw new BaseException("业务覆盖城市太长");
			}
			if (!Strings.isNullOrEmpty(driver.getName()))
				if (!RegexUtil.check(RegexUtil.REGEX_UNICODECHAR, driver.getName()))
					throw new BaseException("车主姓名不合法");
			Driver mobileExistDriver = this.getMobileExistDriver(driver);
			if (Objects.nonNull(mobileExistDriver))
				throw new BaseException(DriverExceptionEnum.DRIVER_MOBLIE_EXIST.getCode(), "该手机号已被使用");
			if (Objects.isNull(driver.getLspId())) throw new BaseException("未选择承运商");
			LspInfo lspInfo = lspInfoService.selectById(driver.getLspId());
			if (Objects.nonNull(lspInfo.getId())) {
				driver.setLspId(lspInfo.getId());
				driver.setTenantId(lspInfo.getTenantId());
			}
			//转换服务类型驾照类型
			if (!CollectionUtils.isEmpty(driver.getServiceTypeList())) {
				String sericeType = String.join(";", driver.getServiceTypeList());
				driver.setServiceType(sericeType);
			} else {
				driver.setServiceType("");
			}
			if (!CollectionUtils.isEmpty(driver.getDrivingLicenseTypeList())) {
				String drivingLicenseType = String.join(";", driver.getDrivingLicenseTypeList());
				driver.setDrivingLicenseType(drivingLicenseType);
			} else {
				driver.setDrivingLicenseType("");
			}
			if (!CollectionUtils.isEmpty(driver.getBusinessSiteList())) {
				String businessSite = String.join(";", driver.getBusinessSiteList());
				driver.setBusinessSite(businessSite);
			} else {
				driver.setBusinessSite("");
			}
			// 添加司机基础信息
			if (Objects.isNull(driver.getId())) {
				JwtAccountVO jwtAccount = AccountUtil.getAccountInfoFromSecurityContext();
				driver.setStatus(StatusEnum.DISCONTINUAT.getCode());
				driver.setAuthStatus(AuthStatusEnum.UNAUTHORIZED.getCode());
				if (Objects.nonNull(jwtAccount)) {
					driver.setCreator(jwtAccount.getAccountId());
				}
				driver.setCreateFrom(SourceEnum.LSPM.getText());
				driver.setGmtCreate(new Date());
				this.insert(driver);
				User user = new User();
				user.setName(driver.getName());
				user.setMobile(driver.getMobile());
				user.setDepartment("driver");
				user.setLspId(driver.getLspId());
				if (Objects.nonNull(jwtAccount)) {
					user.setCreateUser(jwtAccount.getAccountId());
					user.setModifiedUser(jwtAccount.getAccountId());
				}
				iUserService.addUser(user);
			} else {
				driver.setGmtUpdate(new Date());
				//当前账户已登记完成并且未开通
				if (Objects.nonNull(driver.getAccountId()) && AuthStatusEnum.UNAUTHORIZED.getCode().equals(driver.getAuthStatus())) {
					uaaUtil.updateMoblie(driver.getAccountId(), driver.getMobile(), authorization);
				}
				this.updateById(driver);
			}
			return driver;
		} catch (BaseException e) {
			LOGGER.error("DriverServiceImpl.updateDriver" + e.getMessage());
			throw e;
		} catch (Exception e) {
			LOGGER.error("DriverServiceImpl.updateDriver" + e.getMessage());
			throw new BaseException("司机信息保存失败");
		}

	}

	/**
	 * 获取司机
	 */
	@Override
	public DriverBasicVO getDriverInfoLine(Long driverId) {
		DriverBasicVO driverLineVO = new DriverBasicVO();
		if (Objects.isNull(driverId)) throw new BaseException("请传入司机信息");
		EntityWrapper<Driver> driverEntityWrapper = new EntityWrapper<>();
		driverEntityWrapper.eq("id", driverId);
		List<Driver> drivers = baseMapper.selectDriverNoTenant(driverEntityWrapper);
		Driver driver = drivers.get(0);
		if (Objects.isNull(driver)) throw new BaseException("未找到对应司机信息");
//        if (Objects.nonNull(driver.getFleetId())) {
//            Fleet fleet = fleetService.selectByIdNoTenant(driver.getFleetId());
//            if (Objects.nonNull(fleet)) {
//                driverLineVO.setFleetName(fleet.getFleetName());
//            }
//        }
		//查询回显司机的身份证信息
		Wrapper<DriverLicense> licenseEW = new EntityWrapper<>();
		licenseEW.eq("driver_id", driverId)
				.eq("license_type_id", TableStatusEnum.STATUS_1.getCode())
				.orderBy("id", false);
		DriverLicense driverLicense = driverLicenseService.selectOneNoTenant(licenseEW);
		if (driverLicense != null) {
			driverLineVO.setCardId(driverLicense.getLicenseId());
		}
		BeanUtils.copyProperties(driver, driverLineVO);
		// 拿司机ID查询车队名
		Fleet fleet = fleetService.selectByResourceIdAndType(TableStatusEnum.STATUS_03.getCode(), driver.getId());
		if (Objects.nonNull(fleet)) {
			driverLineVO.setFleetName(fleet.getFleetName());
			driverLineVO.setFleetId(fleet.getId());
		}
		if (Objects.nonNull(driver.getLspId())) {
			LspInfo lspInfo = lspInfoService.selectById(driver.getLspId());
			if (lspInfo != null) {
				driverLineVO.setLspName(lspInfo.getName());
			}
		}
		//转换服务类型驾照类型
		if (!StringUtils.isEmpty(driverLineVO.getServiceType())) {
			String[] sericeTypeList = driverLineVO.getServiceType().split(";");
			driverLineVO.setServiceTypeList(Lists.newArrayList(sericeTypeList));
		}
		if (!StringUtils.isEmpty(driverLineVO.getDrivingLicenseType())) {
			String[] drivingLicenseTypeList = driverLineVO.getDrivingLicenseType().split(";");
			driverLineVO.setDrivingLicenseTypeList(Lists.newArrayList(drivingLicenseTypeList));
		}
		if (!StringUtils.isEmpty(driverLineVO.getBusinessSite())) {
			String[] businessSiteList = driverLineVO.getBusinessSite().split(";");
			driverLineVO.setBusinessSiteList(Lists.newArrayList(businessSiteList));
		}
		if (Objects.nonNull(driver.getServiceType())) {
			List<ServiceTypeVO> allServiceType = mdmUtil.getAllServiceTypeList();
			String serviceTypeName = driverLineVO.getServiceType();
			for (ServiceTypeVO serviceTypeVO :
					allServiceType) {
				serviceTypeName = serviceTypeName.replaceAll(serviceTypeVO.getCode(), serviceTypeVO.getValue());
			}
			driverLineVO.setServiceTypeName(serviceTypeName);
		}
		return driverLineVO;
	}

	/**
	 * 根据手机获取司机
	 */
	public Driver getMobileExistDriver(Driver driver) {
		Wrapper<Driver> mobileDriverEntity = new EntityWrapper<>();
		mobileDriverEntity.eq("mobile", driver.getMobile().trim());
		if (Objects.nonNull(driver.getId())) mobileDriverEntity.ne("id", driver.getId());
		List<Driver> mobileDriverList = baseMapper.selectDriverNoTenant(mobileDriverEntity);
		if (!CollectionUtils.isEmpty(mobileDriverList)) {
			return mobileDriverList.get(0);
		}
		return null;
	}


	@Override
	public Page<DriverAccountVO> openDriverList(Page<Driver> page, String authorization) {
		Page<DriverAccountVO> pageInfo = new Page<>();
		page.setAsc(false);
		Wrapper<Driver> driverWrapper = new EntityWrapper<>();
		if (!Objects.isNull(page.getCondition())) {
			Object name = page.getCondition().get("name");
			if (!(Objects.isNull(name) || "".equals(name)))
				driverWrapper.like("name", name.toString()).orNew().like("mobile", name.toString());
		}
		List<DriverAccountVO> driverAccountVOList = Lists.newArrayList();
//        Account account = uaaUtil.getLoginAccount();
		driverWrapper.orderBy("gmt_create", false);
		page.setCondition(new HashMap<>());
		Page<Driver> driverList = this.selectPage(page, driverWrapper);
		driverList.getRecords().forEach(driver -> {
			DriverAccountVO driverAccountVO = new DriverAccountVO();
			BeanUtils.copyProperties(driver, driverAccountVO);
			if (driver.getLspId() != null) {
				LspInfo lspInfo = lspInfoService.selectById(driver.getLspId());
				driverAccountVO.setLspName(lspInfo.getName());
			}
			List<NameValuePair> headNamePairs = Lists.newArrayList();
			List<NameValuePair> params = Lists.newArrayList();
			params.add(new BasicNameValuePair("identifier", driver.getMobile()));
			headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
			String result = HttpClientUtil.get(getAccountDredgeUrl, headNamePairs, params, socketTimeout);
			JSONObject jsonObject = JSONObject.parseObject(result);
			if (Integer.valueOf(jsonObject.get("code").toString()) == 0) {
				if (Boolean.valueOf(jsonObject.getJSONObject("data").get("dredge").toString())) {
					driverAccountVO.setAccountStatus("已开通");
				} else {
					driverAccountVO.setAccountStatus("未开通");
				}
				if (!StringUtils.isEmpty(jsonObject.getJSONObject("data").get("identifier")))
					driverAccountVO.setLoginName(jsonObject.getJSONObject("data").get("identifier").toString());
				if (!StringUtils.isEmpty(jsonObject.getJSONObject("data").get("gmtCreate")))
					driverAccountVO.setOpeningTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(jsonObject.getJSONObject("data").get("gmtCreate")));
			}
			driverAccountVOList.add(driverAccountVO);
		});
		BeanUtils.copyProperties(page, pageInfo);
		pageInfo.setRecords(driverAccountVOList);
		return pageInfo;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean transferDriver(Long[] driverIds, Long lspId, Integer isAllTransfer, String authorization) {
		if (driverIds == null || driverIds.length == 0 || StringUtils.isEmpty(lspId) || StringUtils.isEmpty(isAllTransfer))
			throw new BaseException("操作失败");
		List<Long> driverId = Arrays.asList(driverIds);
		LspInfo lspInfo = lspInfoService.selectById(lspId);
		driverId.forEach(id -> {
			Driver oldDriver = baseMapper.selectById(id);
			if (oldDriver.getAccountId() == null) {
				throw new BaseException(-1, "司机" + oldDriver.getName() + "账号不存在！");
			}
			List<DriverCheckin> list = driverCheckinService.selectByNowDayNoTenant(id);
			if (!org.apache.commons.collections4.CollectionUtils.isEmpty(list)) {
				throw new BaseException("司机存在报班信息,不能转移");
			}
			Driver driver = new Driver();
			driver.setTenantId(lspInfo.getTenantId());
			driver.setLspId(lspInfo.getId());
			driver.setFleetId(null);
			driver.setId(id);
			baseMapper.updateDriverLspRelation(driver);
			List<NameValuePair> headNamePairs = Lists.newArrayList();
			headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
			List<NameValuePair> pram = Lists.newArrayList();
			pram.add(new BasicNameValuePair("DriverId", id.toString()));
			String driverWaybill = HttpClientUtil.get(driverWaybillUrl, headNamePairs, pram, socketTimeout);
			if (!StringUtils.isEmpty(driverWaybill)) {
				JSONObject driverWaybillJson = JSONObject.parseObject(driverWaybill);
				if (!Boolean.valueOf(driverWaybillJson.get("data").toString())) {
					throw new BaseException("司机" + oldDriver.getName() + "还有未完成的运单");
				}
			}

			// 删除车队与司机绑定关系
			fleetBindService.deleteFleetBind(id, TableStatusEnum.STATUS_03.getCode());

			DriverCarrierBind driverCarrierBind = new DriverCarrierBind();
			Wrapper<DriverCarrierBind> driverCarrierBindWrapper = new EntityWrapper<>();
			driverCarrierBindWrapper.eq("driver_id", id);
			driverCarrierBind = driverCarrierBindService.selectOne(driverCarrierBindWrapper);
			if (isAllTransfer == 1) { // 全部转移
				if (driverCarrierBind != null) {
					// 删除车队与牵引车绑定关系
					fleetBindService.deleteFleetBind(driverCarrierBind.getCarrierId(), TableStatusEnum.STATUS_01.getCode());

					driverCarrierBind.setTenantId(lspInfo.getTenantId());
					driverCarrierBindService.update(driverCarrierBind, driverCarrierBindWrapper);
					DriverCarrierBindLog driverCarrierBindLog = new DriverCarrierBindLog();
					driverCarrierBindLog.setTenantId(lspInfo.getTenantId());
					driverCarrierBindLog.setDriverId(id);
					driverCarrierBindLog.setCarrierId(driverCarrierBind.getCarrierId());
					driverCarrierBindLog.setGmtCreate(new Date());
					driverCarrierBindLog.setCreator(Long.valueOf(AccountUtil.getAccountInfoFromSecurityContext().getAccountId()));
					driverCarrierBindLogService.insert(driverCarrierBindLog);

					CarrierInfo carrierInfo = new CarrierInfo();
					carrierInfo.setTenantId(lspInfo.getTenantId());
					carrierInfo.setLspId(lspInfo.getId());
					carrierInfo.setId(driverCarrierBind.getCarrierId());
					carrierInfoService.updateLsp(carrierInfo);

					fleetBindService.deleteFleetBind(driverCarrierBind.getCarrierId(), TableStatusEnum.STATUS_01.getCode());
					CarrierTrailerBind carrierTrailerBind = new CarrierTrailerBind();
					Wrapper<CarrierTrailerBind> carrierTrailerBindWrapper = new EntityWrapper<>();
					carrierTrailerBindWrapper.eq("carrier_id", driverCarrierBind.getCarrierId());
					carrierTrailerBind = carrierTrailerBindService.selectOne(carrierTrailerBindWrapper);
					if (carrierTrailerBind != null) {
						// 删除车队与挂车绑定关系
						fleetBindService.deleteFleetBind(carrierTrailerBind.getTrailerId(), TableStatusEnum.STATUS_02.getCode());
						carrierTrailerBind.setTenantId(lspInfo.getTenantId());
						carrierTrailerBindService.update(carrierTrailerBind, carrierTrailerBindWrapper);
						TrailerInfo trailerInfo = new TrailerInfo();
						trailerInfo.setLspId(lspInfo.getId());
						trailerInfo.setTenantId(lspInfo.getTenantId());
						trailerInfo.setId(carrierTrailerBind.getTrailerId());
						trailerInfoService.updateLspInfo(trailerInfo);
						CarrierTrailerBindLog carrierTrailerBindLog = new CarrierTrailerBindLog();
						carrierTrailerBindLog.setTrailerId(carrierTrailerBind.getTrailerId());
						carrierTrailerBindLog.setTenantId(lspInfo.getTenantId());
						carrierTrailerBindLog.setCarrierId(carrierTrailerBind.getCarrierId());
						carrierTrailerBindLog.setGmtCreate(new Date());
						carrierTrailerBindLog.setCreator(Long.valueOf(AccountUtil.getAccountInfoFromSecurityContext().getAccountId()));
						carrierTrailerBindLogService.insert(carrierTrailerBindLog);
						//调整后的信息 推送ERP
						trailerInfoService.authTrailerToERP(carrierTrailerBind.getTrailerId(), authorization);
					}
					// 调整后的信息  推送ERP
					carrierInfoService.carrierToERP(authorization, driverCarrierBind.getCarrierId());
				}
			} else {
				driverCarrierBindService.delete(driverCarrierBindWrapper);
			}
			if (Objects.nonNull(driverCarrierBind)) {
				bingAndUnbingCarrierToOtm(driverCarrierBind.getCarrierId(), authorization);
			}
			//uaa同步状态
			Map<String, String> prams = new HashMap<>();
			prams.put("accountId", oldDriver.getAccountId().toString());
			prams.put("originalTenantId", oldDriver.getTenantId().toString());
			prams.put("newTenantId", lspInfo.getTenantId().toString());
			LOGGER.info("转移更新司机账号 parms :{}" + prams);
			String result = HttpClientUtil.post(uaaUrl + updateTenantOfAccountUrl, headNamePairs, prams, socketTimeout);
			JSONObject jsonObject = JSONObject.parseObject(result);
			if (jsonObject.getInteger("code") != 0) {
				LOGGER.error("转移更新司机账号 error :{}", jsonObject.getString("message"));
				throw new BaseException(-1, "司机" + oldDriver.getName() + "更新账号异常," + jsonObject.getString("message"));
			}
			//转移后重新推一次司机
			driverToOtm(id);
			authDriverToERP(authorization, id);
		});
		return true;
	}

	@Override
	public Integer updateDriverLspRelation(Driver driver) {
		return baseMapper.updateDriverLspRelation(driver);
	}

	@Override
	public List<String> updateDeleteStatus(List<Long> ids, String token) {
		try {
			List<String> msgs = new ArrayList<>();
			if (CollectionUtils.isEmpty(ids)) throw new BaseException("请选择恢复删除的司机");
			for (Long id : ids) {
				String msg = "";
				EntityWrapper<Driver> driverEntityWrapper = new EntityWrapper<>();
				driverEntityWrapper.eq("id", id);
				List<Driver> drivers = baseMapper.selectDriverNoTenant(driverEntityWrapper);
				Driver driver = drivers.get(0);
				if (Objects.isNull(driver)) {
					msg = "司机:" + driver.getName() + ":司机不存在";
					msgs.add(msg);
					continue;
				}
				if (Objects.nonNull(driver.getAccountId())) {
					try {
						RestfulResponse<?> rs = uaaUtil.unlockAccount(driver.getAccountId().toString(), token);
						if (Objects.nonNull(rs)) {
							if (rs.getCode() == -1) {
								msg = "司机:" + driver.getName() + ":" + rs.getMessage();
								msgs.add(msg);
								continue;
							}
						}
					} catch (Exception e) {
						LOGGER.error("DriverServiceImpl.updateDeleteStatus ERROR :" + e.getMessage());
						msg = "司机:" + driver.getName() + ":解锁账号失败";
						msgs.add(msg);
						continue;
					}
				}
				baseMapper.updateDeleteStatus(driverEntityWrapper);
			}
			return msgs;
		} catch (BaseException e) {
			throw e;
		} catch (Exception e) {
			LOGGER.error("DriverServiceImpl.updateDeleteStatus ERROR :" + e.getMessage());
			throw new BaseException("恢复失败");
		}
	}

	@Override
	public DriverToErpVO driverFleetByCarrier(Long id) {
		return baseMapper.driverToErpVO(id);
	}

	public void driverToOtm(long driverId) {
		DriverToErpVO driverToOtm = baseMapper.driverToErpVONoTenant(driverId);
		if (IntegrationEnum.EXPORT.getCode().equals(IntegrationUtil.getIntegrationToOtm())) {
			DriverDTO driverDTO = new DriverDTO();
			BeanUtils.copyProperties(driverToOtm, driverDTO);
			driverDTO.setIdCard(driverToOtm.getLicenseId());
			driverDTO.setIsActive(IntegrationEnum.ISACTIVE.getCode());
			if (!StringUtils.isEmpty(driverToOtm.getTmsDriverNo())) {
				driverDTO.setPersonalLicense(driverToOtm.getSendCarPass());
			}
			if (!StringUtils.isEmpty(driverDTO.getServiceType())) {

				List<TransportationTypeVO> allServiceType = mdmUtil.getAllTransportType();
				String serviceTypeName = driverDTO.getServiceType();
				for (TransportationTypeVO transportationTypeVO :
						allServiceType) {
					serviceTypeName = serviceTypeName.replaceAll(transportationTypeVO.getCode(), transportationTypeVO.getTosCode());
				}
				driverDTO.setServiceType(serviceTypeName);

				String serviceType = mdmUtil.getServiceTypeByCodes(driverDTO.getServiceType());
				driverDTO.setServiceType(integrationUtil.getServiceType(serviceType));

			} else {
				driverDTO.setServiceType("公路");
			}

			Wrapper<FleetBind> fleetBindWrapper = new EntityWrapper<>();
			fleetBindWrapper.eq("resource_id", driverToOtm.getId()).eq("resource_type", "03");
			FleetBind fleetBind = fleetBindService.selectOne(fleetBindWrapper);
			if (Objects.nonNull(fleetBind)) {
				driverDTO.setLspId(fleetBind.getFleetId());
			}
			integrationUtil.exportDriverToOTM(driverDTO);

		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Driver queryDriverCheckInStatus(Long id, Long checkinId, HttpServletRequest request) {
		if (Objects.isNull(id)) throw new BaseException(-1, "司机id为空");
		Wrapper<Driver> wrapper = new EntityWrapper<>();
		wrapper.eq("id", id);
		List<Driver> driverList = baseMapper.selectDriverNoTenant(wrapper);
		if (!CollectionUtils.isEmpty(driverList)) {
			//判断调整报班信息
			String checkInType = request.getHeader("checkInType");
			if (!StringUtils.isEmpty(checkInType) && Objects.nonNull(checkinId)) {
				//将司机报班信息改为已安排
				if (TableStatusEnum.STATUS_CHECK_IN_IU.getCode().equals(checkInType)) {
					EntityWrapper<DriverCheckin> checkInEW = new EntityWrapper<>();
					checkInEW.eq("a.id", checkinId);
					baseMapper.updateDriverCheckInIU(checkInEW);
				} else if (TableStatusEnum.STATUS_CHECK_IN_RC.getCode().equals(checkInType)) {
					HashMap<String, String> params = Maps.newHashMap();
					params.put("checkinId", String.valueOf(checkinId));
					baseMapper.updateDriverCheckInRC(params);
				}
			}
			return driverList.get(0);
		}
		return null;
	}

	@Override
	public List<Driver> queryAuthDriver() {
		Wrapper<Driver> wrapper = new EntityWrapper<>();
		wrapper.eq("auth_status", 1);
		return baseMapper.selectList(wrapper);
	}

	@Override
	public DriverToErpVO isUnlcnFleetDriver(Long driverId, String authorization) {
		if (Objects.isNull(driverId)) {
			throw new BaseException("司机id为空");
		}
		EntityWrapper<DriverCarrierBind> wrapper = new EntityWrapper<>();
		wrapper.eq("driver_id", driverId)
				.orderBy("id", false);
		List<DriverCarrierBind> carrierBinds = driverCarrierBindService.selectListNoTenant(wrapper);
		DriverToErpVO driverToErpVO = null;
		if (!CollectionUtils.isEmpty(carrierBinds)) {
			DriverCarrierBind carrierBind = carrierBinds.get(0);
			EntityWrapper<FleetBindVO> ew = new EntityWrapper<>();
			ew.eq("carrier_id", carrierBind.getCarrierId())
					.orderBy("id", false);
			List<FleetBindVO> bindVOS = fleetBindService.queryFleetBindNoTenant(ew);
			if (!CollectionUtils.isEmpty(bindVOS)) {
				FleetBindVO fleetBindVO = bindVOS.get(0);
				if (!StringUtils.isEmpty(fleetBindVO.getFleetTypeId())
						&& TableStatusEnum.STATUS_1.getCode().equals(fleetBindVO.getFleetTypeId())) {
					driverToErpVO = new DriverToErpVO();
					driverToErpVO.setFleetName(fleetBindVO.getFleetName());
					driverToErpVO.setName(fleetBindVO.getDriverName());
					driverToErpVO.setMobile(fleetBindVO.getDriverMobile());
					driverToErpVO.setFleetId(fleetBindVO.getFleetId());
				}
			}
		} else {
			// 基于车队层级注册后的关联关系
			EntityWrapper<FleetBind> fbEW = new EntityWrapper<>();
			fbEW.eq("resource_id", driverId)
					.eq("resource_type", TableStatusEnum.STATUS_03.getCode())
					.orderBy("id", false);
			List<FleetBind> fleetBinds = fleetBindService.selectListNoTenant(fbEW);
			if (!CollectionUtils.isEmpty(fleetBinds)) {
				FleetBind fleetBind = fleetBinds.get(0);
				Fleet fleet = fleetService.selectByIdNoTenant(fleetBind.getFleetId());
				if (fleet != null && !StringUtils.isEmpty(fleet.getFleetTypeId())
						&& TableStatusEnum.STATUS_1.getCode().equals(String.valueOf(fleet.getFleetTypeId()))) {
					driverToErpVO = new DriverToErpVO();
					Driver driver = baseMapper.selectByIdNoTenant(driverId);
					if (driver != null) {
						driverToErpVO.setName(driver.getName());
						driverToErpVO.setMobile(driver.getMobile());
					}
					driverToErpVO.setFleetName(fleet.getFleetName());
					driverToErpVO.setFleetId(fleet.getId());
				}
			}
		}
		return driverToErpVO;
	}

	/**
	 * 根据司机名称获取司机信息
	 */
	@Override
	public Map<Long, Driver> queryDriverByName(List<ArFundDTO> arFundDTOS) {
		Map<Long, Driver> map = Maps.newHashMap();
		if (!CollectionUtils.isEmpty(arFundDTOS)) {
			for (ArFundDTO arFundDTO : arFundDTOS) {
				if (!Objects.isNull(arFundDTO)) {
					if (!StringUtils.isEmpty(arFundDTO.getDriverName())) {
						EntityWrapper<Driver> ew = new EntityWrapper<>();
						ew.eq("name", arFundDTO.getDriverName());
						List<Driver> list = baseMapper.selectDriverNoTenant(ew);
						if (!CollectionUtils.isEmpty(list))
							map.put(arFundDTO.getId(), list.get(0));
					}
				}
			}
		}
		return map;
	}

	@Override
	public List<Driver> getDriverAll(List<Driver> driverDTOs) {
		if (driverDTOs.isEmpty()) return null;
		List<Driver> list = Lists.newArrayList();
		driverDTOs.forEach(driver -> {
			HashMap<String, Object> map = Maps.newHashMap();
			if (!StringUtils.isEmpty(driver.getName())) {
				map.put("name", driver.getName());
			}
			if (!StringUtils.isEmpty(driver.getMobile())) {
				map.put("mobile", driver.getMobile());
			}
			if (!StringUtils.isEmpty(driver.getSendCarPass())) {
				map.put("sendCarPass", driver.getSendCarPass());
			}
			EntityWrapper<Driver> ew = this.queryCheck(map);
			Driver resultData = baseMapper.getDriverNoTenant(ew);
			if (!ObjectUtils.isEmpty(resultData)) {
				list.add(resultData);
			}
		});
		return list;
	}

	/**
	 * 查询条件
	 *
	 * @param condition 查询字段
	 */
	private EntityWrapper<Driver> queryCheck(Map<String, Object> condition) {
		EntityWrapper<Driver> ew = new EntityWrapper<>();
		if (!CollectionUtils.isEmpty(condition)) {
			//手机号
			if (condition.containsKey("sendCarPass"))
				ew.eq("send_car_pass", String.valueOf(condition.get("sendCarPass")));
			//遍历条件
			for (Map.Entry<String, Object> entry : condition.entrySet()) {
				if (!Strings.isNullOrEmpty(entry.getKey())) {
					//司机名称
					if ("name".equals(entry.getKey()) && !StringUtils.isEmpty(entry.getValue()))
						ew.eq("name", String.valueOf(entry.getValue()));
					//手机号
					if ("mobile".equals(entry.getKey()) && !StringUtils.isEmpty(entry.getValue()))
						ew.eq("mobile", String.valueOf(entry.getValue()));
				}
			}
		}
		return ew;
	}

	/**
	 * 根据名称和手机号获取所有司机信息
	 */
	@Override
	public List<Driver> queryDriverByCorpName(String corpName) {
		EntityWrapper<Driver> e = new EntityWrapper<>();
		e.like("name", corpName)
				.or()
				.like("mobile", corpName);
		return baseMapper.selectDriverNoTenant(e);
	}

	/**
	 * 根据司机手机号获取司机信息 包含承运商/车队信息
	 */
	@Override
	public DriverDTO queryDriverWithFleet(String mobile) {
		Wrapper<DriverDTO> drEW = new EntityWrapper<>();
		drEW.eq("a.mobile", mobile)
				.eq("a.is_delete", TableStatusEnum.STATUS_0.getCode())
				.orderBy("a.id", false);
		DriverDTO driverDTO = baseMapper.queryDriverFleetNoTenant(drEW);
		if (driverDTO != null) {
			return driverDTO;
		} else {
			//通过牵引车找司机的车队信息
			DriverDTO res = new DriverDTO();
			EntityWrapper<Driver> driverEW = new EntityWrapper<>();
			driverEW.eq("mobile", mobile)
					.eq("is_delete", TableStatusEnum.STATUS_0.getCode())
					.orderBy("id", false);
			List<Driver> drivers = baseMapper.selectDriverNoTenant(driverEW);
			if (!CollectionUtils.isEmpty(drivers)) {
				Driver driver = drivers.get(0);
				res.setId(driver.getId());
				res.setName(driver.getName());
				res.setTenantId(String.valueOf(driver.getTenantId()));
				res.setMobile(mobile);
				res.setLspId(driver.getLspId());
				//承运商信息
				if (!StringUtils.isEmpty(driver.getLspId())) {
					LspInfo lspInfo = lspInfoService.selectByIdNoTenant(driver.getLspId());
					if (lspInfo != null) {
						res.setLspName(lspInfo.getName());
					}
				}
				//车队信息
				EntityWrapper<DriverCarrierBind> dcEW = new EntityWrapper<>();
				dcEW.eq("driver_id", driver.getId())
						.orderBy("id", false);
				List<DriverCarrierBind> binds = driverCarrierBindService.selectListNoTenant(dcEW);
				if (!CollectionUtils.isEmpty(binds)) {
					DriverCarrierBind carrierBind = binds.get(0);
					EntityWrapper<FleetBind> flEW = new EntityWrapper<>();
					flEW.eq("resource_id", carrierBind.getCarrierId())
							.eq("resource_type", TableStatusEnum.STATUS_01.getCode())
							.orderBy("id", false);
					List<FleetBind> bindList = fleetBindService.selectListNoTenant(flEW);
					if (!CollectionUtils.isEmpty(bindList)) {
						FleetBind fleetBind = bindList.get(0);
						EntityWrapper<Fleet> fleetEW = new EntityWrapper<>();
						Fleet fleet = fleetService.selectByIdNoTenant(fleetBind.getFleetId());
						if (fleet != null) {
							//设置车队ID和车队名
							res.setFleetId(fleet.getId());
							res.setFleetName(fleet.getFleetName());
							return res;
						}
					}
				}
			}
			return null;
		}
	}

	@Override
	public Driver selectByIdNoTenant(Long id) {
		return baseMapper.selectByIdNoTenant(id);
	}

	/**
	 * 无车承运人获取司机-车辆-承运商信息
	 */
	@Override
	public DriverBasicDTO queryDriverBasic(Map<String, String> commonDTO) {
		if (commonDTO == null || commonDTO.isEmpty()) {
			throw new BaseException("参数不能为空");
		}
		String driverId = commonDTO.get("driverId");
		if (!StringUtils.isEmpty(driverId)) {
			Driver driver = baseMapper.selectByIdNoTenant(Long.valueOf(driverId));
			if (driver != null) {
				DriverBasicDTO basicDTO = new DriverBasicDTO();
				//获取基础信息
				BeanUtils.copyProperties(driver, basicDTO);
				EntityWrapper<DriverLicense> licenseEW = new EntityWrapper<>();
				licenseEW.eq("driver_id", driverId);
				List<DriverLicense> licenses = driverLicenseService.selectListNoTenant(licenseEW);
				basicDTO.setDriverLicenseList(licenses);
				//获取承运商
				LspInfo lspInfo = lspInfoService.selectByIdNoTenant(driver.getLspId());
				if (lspInfo != null) {
					basicDTO.setLspName(lspInfo.getName());
					basicDTO.setLspCreate(lspInfo.getGmtCreate());
					EntityWrapper<LspLicense> llEW = new EntityWrapper<>();
					llEW.eq("lsp_id", lspInfo.getId())
							.orderBy("id", false);
					List<LspLicense> lspLicenses = lspLicenseService.selectListNoTenant(llEW);
					basicDTO.setLspLicenses(lspLicenses);
				}
				//查询绑定牵引车
				EntityWrapper<DriverCarrierBind> dcEW = new EntityWrapper<>();
				dcEW.eq("driver_id", driver.getId())
						.orderBy("id", false);
				List<DriverCarrierBind> binds = driverCarrierBindService.selectListNoTenant(dcEW);
				if (!CollectionUtils.isEmpty(binds)) {
					DriverCarrierBind carrierBind = binds.get(0);
					List<WeChatVehicle> weChatVehicles = carrierInfoService.selectVehicleByCarrierIdOrTrailerIdNoTenant(carrierBind.getCarrierId(), null);
					if (!CollectionUtils.isEmpty(weChatVehicles)) {
						WeChatVehicle vehicle = weChatVehicles.get(0);
						basicDTO.setCarrierOwner(vehicle.getOwnerName());
						basicDTO.setCarrierCreate(vehicle.getGmtCreate());
						basicDTO.setCarrierPlate(vehicle.getPlate());
						basicDTO.setTrailerPlate(vehicle.getTrailerPlate());
						if (vehicle.getSelfWeight() != null) {
							basicDTO.setCarrierSelfWeight(String.valueOf(vehicle.getSelfWeight()));
						}
					}
					// 查carrierLicense
					EntityWrapper<CarrierLicense> clEW = new EntityWrapper<>();
					clEW.eq("carrier_id", carrierBind.getCarrierId())
							.orderBy("id", false);
					List<CarrierLicense> carrierLicenses = licenseService.selectListNoTenant(clEW);
					if (!CollectionUtils.isEmpty(carrierLicenses)) {
						basicDTO.setCarrierLicenses(carrierLicenses);
					}
				}
				return basicDTO;
			}
		}
		return null;
	}

	@Override
	public List<Driver> selectListNoTenant(Wrapper<Driver> driverWrapper) {
		return baseMapper.selectDriverNoTenant(driverWrapper);
	}

	@Override
	public Page<DriverTypeDTO> getDriverList(Page<DriverTypeDTO> page) {
		Page<DriverTypeDTO> pageVo = new Page<>();
		Wrapper<DriverTypeDTO> ew = new EntityWrapper<>();
		Map<String, Object> condition = page.getCondition();
		if (condition != null && !condition.isEmpty()) {
			if (null != condition.get("driverName") && !StringUtils.isEmpty(condition.get("driverName"))) {
				ew.like("driverName", condition.get("driverName").toString());
			}
			if (null != condition.get("lspName") && !StringUtils.isEmpty(condition.get("lspName"))) {
				ew.like("lspName", condition.get("lspName").toString());
			}
			if (null != condition.get("fleetNames") && !StringUtils.isEmpty(condition.get("fleetNames"))) {
				String fleetNames = condition.get("fleetNames").toString();
				String[] fleetNameList = fleetNames.split(",");
				ew.in("fleetName", fleetNameList);
			}

			if (null != condition.get("serviceType") && !StringUtils.isEmpty(condition.get("serviceType"))) {
				if (condition.get("serviceType").toString().equals("10")){
					ew.eq("serviceType", "driver");
				}
				if (condition.get("serviceType").toString().equals("20")){
					ew.eq("serviceType", "fleet");
				}
			}
			if (null != condition.get("mobile") && !StringUtils.isEmpty(condition.get("mobile"))) {
				ew.eq("mobile", condition.get("mobile").toString());
			}
			List<DriverTypeDTO> driverTypeDTOs = baseMapper.selectDriverTypeList(page, ew);
			for (DriverTypeDTO driverTypeDTO : driverTypeDTOs) {
				if ((driverTypeDTO.getServiceType().indexOf("driver")) >= 0) {
					driverTypeDTO.setServiceType("人送司机");
				}
				if ((driverTypeDTO.getServiceType().indexOf("fleet")) >= 0) {
					driverTypeDTO.setServiceType("板车司机");
				}
			}
			BeanUtils.copyProperties(page, pageVo);
			pageVo.setRecords(driverTypeDTOs);
			return pageVo;
		}
		return pageVo;
	}

	@Override
	public List<Driver> selectByLspId(String lspId) {
		return baseMapper.selectByLspId(lspId);
	}

	@Override
	public Driver selectDriverByFleetBindId(Long fleetBindId) {
		return baseMapper.selectDriverByFleetBindId(fleetBindId);
	}
}
